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

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

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



$responseStream = $response.GetResponseStream()

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

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

$read = 0
while ($read -ne 0)

By the way, this is not me. It's just someone that is using my words without citation.
  1. Prémio Dardos, para este blogue :http://muitaterra.blogspot.com/2008/10/movimentos-outros.html

  2. I know this is an old post, but I am trying to just get a directory listing of an ftp server and I keep getting an error on $response=$ftp.GetResponse()
    Exception calling "GetResponse" with "0" argument(s): "Timeout"

    What can cause this error? I've been scouring the net for answers and can find none at all.

  3. I think I would run a sniffer like wireshark or ms network monitor and see what's happening at tcp/ip level. It might be an actual timeout

  4. The JAMS Job Scheduler provides some cmdlets for secure FTP connections. You can list directory contents and automate transfers easily.