Today I had to download around 900 files from ftp server, however firewall was blocking almost everything, however I was able to access the FTP server via web browser (I used one and only IE :)). So a colleague advised me to use wget to download the files, but I’m a kind of MS guy and I’m not get used to using wget, so I decided to use powershell. So I’d like to present you how easy it is to download the files using powershell (I’m using v.2). What I need are 2 .NET classes [System.Net.Webclient] and because I’m going through proxy [System.Net.Webproxy]. All my files were placed in one folder on ftp server and I wanted download them to predefined folder – that’s my input data, so the simple script goes like that
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
#Creating WebClient object $wc = New-Object system.Net.WebClient; #Creating WebProxy object $wp = New-Object System.Net.WebProxy("http://your_proxy_server:port",$true) #Credentials needed to authenticate on proxy server $wp.Credentials = Get-Credential #Defining proxy on WebClient object $wc.Proxy = $WebProxy #Credentials needed to authenticate on FTP server $wc.Credentials = Get-Credential #Defining the server name and folder where files are located $ftp_server_prefix = "ftp://server_address/folder_name/" #Defining the destination folder $destination_prefix = "c:\files\" #Input file name (my file containing the files to downlad) $inputFile = "C:\files_to_download.txt" #and we go with the loop gc $inputFile | % { $wc.DownloadFile(($ftp_server_prefix + $_),($destination_prefix + $_)) } |
As you can see it’s pretty easy, there are more comments and input definitions than scripting.