GET Ftp File function


posted by Sylvain LESIRE
01-06-2009

Downloads: 1,900
File size: 1.3kB
Views: 27,901

Embed
GET Ftp File function
  1. function Get-FTPFile ($Source,$Target,$UserName,$Password
  2.  
  3. # Create a FTPWebRequest object to handle the connection to the ftp server 
  4. $ftprequest = [System.Net.FtpWebRequest]::create($Source
  5.  
  6. # set the request's network credentials for an authenticated connection 
  7. $ftprequest.Credentials = 
  8.     New-Object System.Net.NetworkCredential($username,$password
  9.  
  10. $ftprequest.Method = [System.Net.WebRequestMethods+Ftp]::DownloadFile 
  11. $ftprequest.UseBinary = $true 
  12. $ftprequest.KeepAlive = $false 
  13.  
  14. # send the ftp request to the server 
  15. $ftpresponse = $ftprequest.GetResponse() 
  16.  
  17. # get a download stream from the server response 
  18. $responsestream = $ftpresponse.GetResponseStream() 
  19.  
  20. # create the target file on the local system and the download buffer 
  21. $targetfile = New-Object IO.FileStream ($Target,[IO.FileMode]::Create
  22. [byte[]]$readbuffer = New-Object byte[] 1024 
  23.  
  24. # loop through the download stream and send the data to the target file 
  25. do
  26.     $readlength = $responsestream.Read($readbuffer,0,1024) 
  27.     $targetfile.Write($readbuffer,0,$readlength
  28. while ($readlength -ne 0) 
  29.  
  30. $targetfile.close() 
  31.  
  32. $sourceuri = "ftp://MyFtpServer/FolderPath\File.txt" 
  33. $targetpath = "C:\temp\MyFile.txt" 
  34. $user = "Username" 
  35. $pass = "Password" 
  36. Get-FTPFile $sourceuri $targetpath $user $pass 

This script show you how to Get File from a FTP Server.

This script was a modification from a script find on :

http://stackoverflow.com/questions/265339/whats-the-best-way-to-automate-secure-ftp-in-powershell

You can use SSL on your script by using

$ftprequest.EnableSsl = $true                  # line 15 Wink

Copyright 2012 PowerShell.com. All rights reserved.