PowerShell/Scripts/upload-file.ps1

56 lines
1.9 KiB
PowerShell
Raw Normal View History

2021-04-21 19:53:52 +02:00
<#
2021-04-14 10:23:14 +02:00
.SYNTAX upload-file.ps1 [<file>] [<URL>] [<username>] [<password>]
.DESCRIPTION uploads the local file to the given FTP server
.LINK https://github.com/fleschutz/PowerShell
.NOTES Author: Markus Fleschutz / License: CC0
#>
param($File = "", $URL = "", $Username = "", $Password = "")
2021-04-21 19:53:52 +02:00
2021-04-14 10:23:14 +02:00
if ($File -eq "") { $File = read-host "Enter local file to upload" }
if ($URL -eq "") { $URL = read-host "Enter URL of FTP server" }
if ($Username -eq "") { $Username = read-host "Enter login username" }
if ($Password -eq "") { $Password = read-host "Enter login password" }
try {
2021-04-15 08:41:37 +02:00
$StopWatch = [system.diagnostics.stopwatch]::startNew()
2021-04-14 10:23:14 +02:00
# check local file first:
if (-not(test-path "$File" -pathType leaf)) { throw "Can't access file: $File" }
2021-04-23 09:11:39 +02:00
$FullPath = Resolve-Path "$File"
2021-04-14 10:23:14 +02:00
$Filename = (Get-Item $File).Name
2021-04-14 10:43:48 +02:00
$FileSize = (Get-Item $File).Length
"Local file: $FullPath ($FileSize bytes)"
2021-04-14 10:23:14 +02:00
$request = [Net.WebRequest]::Create("$URL/$Filename")
$request.Credentials = New-Object System.Net.NetworkCredential("$Username", "$Password")
$request.Method = [System.Net.WebRequestMethods+Ftp]::UploadFile
$request.EnableSSL = $false
$request.KeepAlive = $true
$request.UseBinary = $true
2021-04-23 09:11:39 +02:00
$request.UsePassive = $true
2021-04-14 10:23:14 +02:00
$fileStream = [System.IO.File]::OpenRead("$FullPath")
$ftpStream = $request.GetRequestStream()
2021-04-14 10:43:48 +02:00
"Uploading ..."
2021-04-23 09:11:39 +02:00
$Buf = New-Object Byte[] 64KB
while (($DataRead = $fileStream.Read($Buf, 0, $Buf.Length)) -gt 0)
2021-04-14 10:43:48 +02:00
{
2021-04-23 09:11:39 +02:00
$ftpStream.Write($Buf, 0, $DataRead)
2021-04-14 10:43:48 +02:00
$pct = ($fileStream.Position / $fileStream.Length)
Write-Progress -Activity "Uploading" -Status ("{0:P0} complete:" -f $pct) -PercentComplete ($pct * 100)
}
2021-04-14 10:23:14 +02:00
# cleanup:
$ftpStream.Dispose()
$fileStream.Dispose()
2021-04-21 16:43:08 +02:00
[int]$Elapsed = $StopWatch.Elapsed.TotalSeconds
2021-04-23 09:11:39 +02:00
"✔️ uploaded $Filename to $URL in $Elapsed sec."
2021-04-14 10:23:14 +02:00
exit 0
} catch {
write-error "ERROR: line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
exit 1
}