PoshCode Logo PowerShell Code Repository

Send-FTP 1.0 by Joel Bennett 30 months ago
View followups from rikka | embed code: <script type="text/javascript" src="http://PoshCode.org/embed/1240"></script>download | new post

A little Send-FTP script to support uploading files. This version is simple: it can’t create folders nor allow you to specify whether to overwrite files …

  1.    function Send-FTP {
  2.       Param(
  3.          $Server = "ilncenter.net"
  4.       ,  $Credentials = $(Get-Credential)
  5.       ,  [Parameter(ValueFromPipeline=$true)]
  6.          $LocalFile
  7.       ,  $Path = "/"
  8.       ,  $RemoteFile = $(Split-Path $LocalFile -Leaf)
  9.       ,  $ParentProgressId = -1 ## Just ignore this ;)
  10.       ,  $ProgressActivity = "Uploading $LocalFile"
  11.       )
  12.       Process {
  13.          ## Assert the existence of the file in question
  14.          if( -not (Test-Path $LocalFile) ) {
  15.             Throw "File '$LocalFile' does not exist!"
  16.          }
  17.  
  18.          ## Create the server string (and make sure it uses forward slashes and ftp://)
  19.          $upload = "ftp://" + $Server + ( Join-Path (Join-Path "/" $Path) $RemoteFile ) -replace "\\", "/"
  20.          #$Upload = $upload
  21.          $total = (gci $LocalFile).Length
  22.  
  23.          Write-Debug $upload
  24.          ## Create FTP request
  25.          $request = [Net.FtpWebRequest]::Create($upload)
  26.  
  27.          ## NOTE: we do not create a folder here...
  28.          # [System.Net.WebRequestMethods+Ftp]::MakeDirectory
  29.          $request.Method = [System.Net.WebRequestMethods+Ftp]::UploadFile
  30.          $request.Credentials = $Credentials.GetNetworkCredential()
  31.          $request.UsePassive = $true
  32.          $request.UseBinary = $true
  33.          $request.KeepAlive = $false
  34.  
  35.          try {
  36.             ## Load the file
  37.             $read = [IO.File]::OpenRead( (Convert-Path $LocalFile) )
  38.             $write = $request.GetRequestStream();
  39.            
  40.             $buffer = new-object byte[] 20KB
  41.             $offset = 0
  42.             $progress = 0
  43.  
  44.             do {
  45.                $offset = $read.Read($buffer, 0, $buffer.Length)
  46.                $progress += $offset
  47.                $write.Write($buffer, 0, $offset);
  48.                Write-Progress $ProgressActivity "Uploading" -Percent ([int]($progress/$total * 100)) -Parent $ParentProgressId
  49.             } while($offset -gt 0)
  50.        
  51.          } finally {
  52.             Write-Debug "Closing Handles"
  53.             $read.Close()
  54.             $write.Close()
  55.          }
  56.       }
  57.    }

Submit a correction or amendment below (
click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.

Syntax highlighting:


Remember me