Connect to SFTP using Powershell and PSFTP

Quick post on how to use sftp with powershell via PSFTP.  The jist of it, is you connect to the sftp server, do an ls (the ls command is contained within an sftp file) and from there use powershell to filter the files you want.  While filtering the files, you write the commands (get, in this case) to a command file.  You then re-connect to the sftp server and execute the commands in the sftp file you just created.  I did look to another post to give me a clue as to how to accomplish this, but I can’t seem to find the site to give proper attribution. 

$Error.Clear();
$location = 'c:\FtpFilesDownloaded'
$ignore = @('quit', '/bdn483', '.', '..', '.ssh', 'ls')  #ignore these commands in the return when doing an ls to build the 'get' batch file
$ftpUser = 'ftpUserName'
$ftpPassword = 'ftpPassword'
$ftpGetCommandFile = 'C:\ftpGetCommand.sftp'  #just an ls command
sl $location

if(Test-Path $ftpGetCommandFile){
	Remove-Item $ftpGetCommandFile
}
ls $location | %{  #remove all files in local download location
	Remove-Item $_
}

$lsFiles = & C:\psftp.exe -l $ftpUser -pw $ftpPassword  ftp.ftplocation.com -b C:\lsCommand.sftp -be #the lsCommand just contains an ls command
if($LastExitCode -ne 0){
	throw "Error connecting to ftp..."
}
$colActiveRemoteFiles = $lsFiles | %{$_.Split()[-1]}
$colActiveRemoteFiles | where {$ignore -notcontains $_ } | %{
	"get $_" | Out-File $ftpGetCommandFile -Append -Encoding Ascii
}
& c:\psftp.exe -l $ftpUser -pw $ftpPassword  ftp.ftplocation.com -b c:\ftpGetCommands.sftp -be -bc
if($LastExitCode -ne 0){
	throw "Error downloading files.  "
}
Advertisements

2 Comments on “Connect to SFTP using Powershell and PSFTP

  1. Pingback: Using Powershell to access FTP Server - HTML CODE

  2. Thank you, nice little script! The cleverness to retrieve the pure file list opens up a lot of possibilities for basic sftp operations within Powershell using the simple PSFTP executable.

    One suggestion: Include the -batch switch when calling psftp from Powershell or other automation context. Otherwise the command will hang when there is an error. Reference: http://the.earth.li/~sgtatham/putty/0.52/htmldoc/Chapter6.html#6.1.8

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: