2008-10-16

PowerShell: very simple FTP client

One of my first experiments with PowerShell, besides ls and HelloWorld.ps1, was trying the object oriented features and the .Net Framework. I was at the time thinking about a problem I was having with an FTP client I was using and I asked myself: "Would it be possible to make an FTP client with PowerShell?"

I knew there was a .Net class that implemented an FTP client so I googled and bit and found it. After reading the examples shown and a little try-and-error, I came up with this extremely simple FTP client in PowerShell below. Note that by "extremely simple" I mean "with very few features and no error detection code". This only gets one file from the FTP server. I probably wouldn't use this in production without a few changes. But it's still a nice example on how to use the .Net framework with PowerShell and this class in particular


$localfile = "c:\file.txt"
$remotefile = "/folder/file.txt"
$ftphost = "ftp://ftpserver"
$URI = $ftphost + $remotefile
$username="username"
$password="password"


function Get-FTPFile ($URI,$localfile,$username,$password){

$credentials=New-Object System.Net.NetworkCredential($username,$password)



$ftp=[System.Net.FtpWebRequest]::Create($URI)

$ftp.Credentials=$credentials
$ftp.UseBinary=1
$ftp.KeepAlive=0


$response=$ftp.GetResponse()
$responseStream = $response.GetResponseStream()

$file = New-Object IO.FileStream ($localfile,[IO.FileMode]::Create)

[byte[]]$buffer = New-Object byte[] 1024

$read = 0
do{
$read=$responseStream.Read($buffer,0,1024)
$file.Write($buffer,0,$read)
}
while ($read -ne 0)
$file.close()
}



PS:
By the way, this is not me. It's just someone that is using my words without citation.