Skip to content

Upload files to an SFTP server via PowerShell

G11th November 2016

C1 Comment

TPowerShell

Easily transfer files from a local drive to a Secure File Transfer Protocol (SFTP) server using PowerShell. This script is useful for automating file transfers.

I needed to regularly back-up a series of files to a Secure File Transfer Protocol (SFTP) server.

To make this process easier, I wrote a PowerShell script which will effectively automate the process. The script will upload my files into a new folder which is named after today’s date (in the format yyyyMMdd).

All I need do is execute the script and my work is done!

The script requires an installation of the WinSCP .NET Assembly to work. The WinSCP .NET Assembly can be downloaded for free from the WinSCP website.

Before executing the script, the following parameters need to be customised:

  1. The path to WinSCPnet.dll on the local machine
  2. The SFTP server name (a friendly name; this can be anything such as an IP address, server name or something else)
  3. The username
  4. The SSH server key fingerprint
  5. The location of the files to be uploaded (plus any rules, eg *.txt)
  6. The target directory for the files on the SFTP server

The script will then complete the upload task by:

  1. Prompting for the user’s password (this is not hard-coded as a security measure, but can be)
  2. Logging onto the SFTP server
  3. Locating the target directory on the SFTP server and creating a new subdirectory with the format /yyyyMMdd (you can customise this)
  4. Uploading the target files to the new directory
  5. Informing the user that the files have been uploaded
  6. Ending the session

I recommend saving this script as a .ps1 file and executing it via a batch file for simplicity.

#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()
}

This code has also been uploaded to Github Gist.

   

Comments:

One response to “Upload files to an SFTP server via PowerShell”

  • Written by Gerhard on 18 December 2018:
    $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"
    }

    when using the above block from the script, PowerShell throws an error, stating that the given value or property is Write-protected.
    + $sessionOptions = New-Object WinSCP.SessionOptions -Property @{

    this makes the other properties also fail to be set properly.

Have your say:

The following HTML is permitted:
<a href="" title=""> <b> <blockquote cite=""> <code> <em> <i> <q cite=""> <strike> <strong>

Comments will be published subject to the Editorial Policy.