Skip to content

Instantly share code, notes, and snippets.

@AdamDimech
Last active April 11, 2021 17:07
  • Star 0 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save AdamDimech/3cb20000d965743a256c5c9aaeeda75a to your computer and use it in GitHub Desktop.
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
Copy link

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