Skip to content

Instantly share code, notes, and snippets.

@hackerman518
Forked from AdamDimech/SFTP-Upload.ps1
Created June 24, 2019 05:57
Show Gist options
  • Select an option

  • Save hackerman518/693bac60524edb773c49d6aa92974889 to your computer and use it in GitHub Desktop.

Select an option

Save hackerman518/693bac60524edb773c49d6aa92974889 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()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment