Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Upload files to an SFTP server via PowerShell
#Upload files to an SFTP server via PowerShell
#Requires WinSCP to be installed on local machine
# Load WinSCP .NET assembly
Add-Type -Path "C:\path\to\WinSCPnet.dll"
# Password prompt (not obscured)
[void][Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic')
$title = 'Credentials'
$msg = 'Enter your password:'
$pass = [Microsoft.VisualBasic.Interaction]::InputBox($msg, $title)
# Display name of server
$servername = "FTP Server Descriptive Name"
# Set up session options
$sessionOptions = New-Object WinSCP.SessionOptions -Property @{
Protocol = [WinSCP.Protocol]::Sftp
HostName = "ftp.mywebsite.com.au"
UserName = "username"
Password = $pass
SshHostKeyFingerprint = "ssh-rsa 2048 xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx"
}
$sessionOptions.AddRawSettings("AuthGSSAPI", "1")
$sessionOptions.AddRawSettings("TcpNoDelay", "1")
$sessionOptions.AddRawSettings("FSProtocol", "2")
$session = New-Object WinSCP.Session
try
{
# Connect
$session.Open($sessionOptions)
#Message
Write-Host -ForegroundColor Cyan "`r`nUploading files to $servername..."
Write-Host -ForegroundColor White "Do not close this window!"
# Create folder
$date = $((Get-Date).ToString('yyyyMMdd'))
$path = "/path/to/target/"+($date)+"/"
$session.CreateDirectory($path)
# Transfer files
$session.PutFiles("c:\path\to\files\*.*", $path+"/*").Check()
}
finally
{
#Inform user
[System.Windows.Forms.MessageBox]::Show("Files have been uploaded to $servername.")
#Dispose of sesssion
$session.Dispose()
}
@mhabib1981

This comment has been minimized.

Copy link

mhabib1981 commented Nov 7, 2019

Hi thanks for the script.
Can you please write for SFTP as well

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.