Last active
April 11, 2021 17:07
-
-
Save AdamDimech/3cb20000d965743a256c5c9aaeeda75a to your computer and use it in GitHub Desktop.
Upload files to an SFTP server via PowerShell
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi thanks for the script.
Can you please write for SFTP as well