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.  "
}

2 thoughts on “Connect to SFTP using Powershell and PSFTP

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 )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.