HOWTO: Using FTP or SFTP in PowerShell

  |   Lukas Matyska

PowerShell - a powerful new scripting language and command shell from Microsoft - has many built-in commands. However, it lacks support for transferring files over FTP, FTP/SSL or SFTP. Luckily, PowerShell is based on .NET and can invoke methods of .NET classes. Let's see how to upload or download files to an FTP or SFTP server from a PowerShell script using either Rebex FTP/SSL) or Rebex SFTP component.

Step 0 - Download assemblies

Before you begin, you would need to get SFTP or FTP .NET assemblies. Both of them are included in Rebex File Transfer Pack.

Download Rebex File Transfer Pack (FTP and SFTP .NET component)

Step 1 - Loading FTP or SFTP assembly

First, we have to load Rebex assemblies via [Reflection.Assembly]::LoadFrom command. You can load Rebex.Ftp.dll for FTP or FTP/SSL, Rebex.Sftp.dll for Rebex SFTP (or Rebex.FileTransfer.dll for both protocols). Other dependent assemblies will be loaded automatically as well. Of course, make sure the path to the assemblies matches our install path.

PS C:\> [Reflection.Assembly]::LoadFrom("C:\Program Files (x86)\Rebex Components 2015 R4.1\bin\net-4.0\Rebex.Ftp.dll")

GAC    Version        Location
---    -------        --------
False  v4.0.30319     C:\Program Files (x86)\Rebex Components 2015 R4.1\bin\net-4.0\Rebex.Ftp.dll

Step 2 - Connecting, logging in, uploading, downloading and deleting files

Now, you can call the FTP methods as described in the FTP Tutorial:

PS C:\> [Reflection.Assembly]::LoadFrom("C:\Program Files (x86)\Rebex Components 2015 R4.1\bin\net-4.0\Rebex.Ftp.dll")

GAC    Version        Location
---    -------        --------
False  v4.0.30319     C:\Program Files (x86)\Rebex Components 2015 R4.1\bin\net-4.0\Rebex.Ftp.dll

PS C:\> $ftp = New-Object Rebex.Net.Ftp
PS C:\> $ftp.Connect("test.rebex.net")
220 FTP on test.rebex.net ready...

PS C:\> $ftp.Login("demo", "password")
230 User demo logged in.

PS C:\> $ftp.PutFile("C:\temp\test.txt", "test.txt")
89
PS C:\> $ftp.GetFile("test.txt", "C:\temp\test2.txt")
89
PS C:\> $ftp.DeleteFile("test.txt")
PS C:\> $ftp.Disconnect()
221 Goodbye.

PS C:\> $ftp.Dispose()
PS C:\> Remove-Variable ftp
PS C:\>

That's all!

What about GAC?

And in case you would like to load Rebex assemblies from Global Assembly Cache (GAC) instead of from a path, use Assembly.Load method instead:

PS C:\> [Reflection.assembly]::Load("Rebex.Ftp, Version=4.0.5715.0
, Culture=neutral, PublicKeyToken=1c4638788972655d")

GAC    Version        Location
---    -------        --------
True   v2.0.50727     C:\WINDOWS\assembly\GAC\Rebex.Ftp\4.0.5715.0__1c4638788972655d\Rebex.Ftp.dll