Skip to content

Instantly share code, notes, and snippets.

@fushnisoft
Last active January 19, 2022 08:03
Show Gist options
  • Save fushnisoft/5591405 to your computer and use it in GitHub Desktop.
Save fushnisoft/5591405 to your computer and use it in GitHub Desktop.
Upload a file using powershell and the WinSCP .NET library with upload progress feedback
# Using the beta version of WinSCP http://winscp.net/eng/download.php
# Call this script to upload a file via FTP with progress feedback
# e.g.
# .\fileupload.ps1 -username "myusername" -password "mypassword" -localfile "C:\files\MyFile.exe" -remotefile "/public_html/files/MyFile.exe"
# NOTE: This script assumes the WinSCP binaries are in a sub directory to the script. You can probably pass that as a parameter to be more flexible.
param (
[string]$username,
[string]$password,
[string]$localFile,
[string]$remoteFile
)
Write-Host "Uploading"
function FileProgress
{
Param($e)
if ($e.FileProgress -ne $Null)
{
$transferSpeed = 0
if ($e.CPS -ne $Null)
{$transferSpeed = $e.CPS}
$filePercent = $e.FileProgress*100
Write-Progress -activity "FTP Upload" -status ("Uploading " + $e.FileName) -percentComplete ($filePercent) -CurrentOperation ("Completed: " + $filePercent + "% @ " + [Math]::Round(($transferSpeed/1024),2) + " k/bytes per second")
}
}
try
{
# Load WinSCP .NET assembly
# Use "winscp.dll" for the releases before the latest beta version.
[Reflection.Assembly]::LoadFrom(".\WinSCP\WinSCPnet.dll") | Out-Null
# Setup session options
$sessionOptions = New-Object WinSCP.SessionOptions
$sessionOptions.Protocol = [WinSCP.Protocol]::ftp
$sessionOptions.HostName = "domain.com"
$sessionOptions.UserName = $username
$sessionOptions.Password = $password
$session = New-Object WinSCP.Session
try
{
$session.add_FileTransferProgress( { FileProgress($_) } )
# Connect
$session.Open($sessionOptions)
# Upload files
$transferOptions = New-Object WinSCP.TransferOptions
$transferOptions.TransferMode = [WinSCP.TransferMode]::Binary
$transferResult = $session.PutFiles($localfile, $remoteFile, $False, $transferOptions)
# Throw on any error
$transferResult.Check()
# Print results
foreach ($transfer in $transferResult.Transfers)
{
Write-Host ("Upload of {0} succeeded" -f $transfer.FileName)
}
}
finally
{
# Disconnect, clean up
$session.Dispose()
}
exit 0
}
catch [Exception]
{
Write-Host $_.Exception.Message
exit 1
}
@dannylloyd
Copy link

@OoMaH This might be 6 years too late but I was wondering the same thing and found this in the documentation

int CPS | Transfer speed (bytes per second). Read-only.

https://winscp.net/eng/docs/library_filetransferprogresseventargs#cps

@tafflin
Copy link

tafflin commented Jan 19, 2022

Thanks, very helpful. What is the correct way to print the success status at the end of the transfer?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment