Sunday, 3 October 2010

Copy-FileToFtp.ps1


  1. <# 
  2. .SYNOPSIS 
  3.     This script Uploads a text file to an FTP Server using PowerShell.  
  4. .DESCRIPTION 
  5.     This script first creates an FTP 'web' request to upload a file. Then the  
  6.     source file is read from disk and written up to the FTP Server. A response 
  7.     is then displayed. This is a rewrite of an MSDN Sample. 
  8. .NOTES 
  9.     File Name  : Copy-FileToFtp.ps1 
  10.     Author     : Thomas Lee - tfl@psp.co.uk 
  11.     Requires   : PowerShell Version 2.0 
  12. .LINK 
  13.     This script posted to: 
  14.         http://pshscripts.blogspot.com/2010/10/copy-filetoftpps1.html
  15.     MSDN sample posted tot: 
  16.         http://msdn.microsoft.com/en-us/library/ms229715.aspx
  17. .EXAMPLE 
  18.     PSH [C:\foo]: .Copy-FileToFtp.ps1 
  19.     Upload File Complete, status 226
  20.     226 Transfer complete. 
  21. #> 
  22.   
  23. # Get the object used to communicate with the server. 
  24. $Request = [System.Net.FtpWebRequest]::Create("ftp://www.reskit.net/powershell/Greetings.Txt"
  25. $Request.Method = $Request.Method = [System.Net.WebRequestMethods+ftp]::UploadFile 
  26.  
  27. # This example assumes the FTP site uses anonymous logon. 
  28. $Request.Credentials = New-Object System.Net.NetworkCredential "anonymous","tfl@psp.co.uk" 
  29.  
  30. # Copy the contents of the file to the request stream. 
  31. $FileContents = [System.IO.File]::ReadAllBytes("C:\foo\scriptlib.zip"
  32. $Request.ContentLength = $fileContents.Length
  33. $RequestStream = $request.GetRequestStream() 
  34. $RequestStream.Write($FileContents, 0, $FileContents.Length) 
  35. $RequestStream.Close()
  36. $Response = $Request.GetResponse() 
  37. "Upload File Complete, status {0}" -f $Response.StatusDescription 
  38. $Response.Close()

No comments: