Skip to content

Instantly share code, notes, and snippets.

@jonasnordlund
Created April 6, 2017 10:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonasnordlund/8df5a951f6e7a773609147dc469d3f10 to your computer and use it in GitHub Desktop.
Save jonasnordlund/8df5a951f6e7a773609147dc469d3f10 to your computer and use it in GitHub Desktop.
Transfer files over FTP/HTTP with piping support using Powershell
<#
.SYNOPSIS
Transfers files over HTTP or FTP.
.DESCRIPTION
Downloads or uploads files over HTTP or FTP. Supports user authentication and piped file names.
.PARAMETER UserName
The user account name or an anonymous connection if missing.
.PARAMETER Password
The user account password.
.PARAMETER FileName
The file to transfer. This parameter is used when piping to PSTransfer.
.PARAMETER ServerPath
The remote server directory path.
.PARAMETER LocalPath
The local file directory path or the local directory if missing.
.PARAMETER Action
The transfer to perform, Upload or Download.
.EXAMPLE
.\PSTransfer.ps1 -FileName file.zip -ServerPath ftp://ftp.example.com -Action Download
Downloads file.zip from ftp.example.com into the current folder using an anonymous login.
.EXAMPLE
type files.txt | % { .\PSTransfer.ps1 -UserName john -Password doe -FileName $_ -ServerPath ftp://example.com/ -LocalPath . -Action Download }
Downloads all files listed in files.txt.
#>
param(
[string]$UserName = "anonymous",
[string]$Password = "anonymous@example.com",
[Parameter(Mandatory=$True, ValueFromPipeline=$True)]
[string]$FileName,
[Parameter(Mandatory=$True)]
[string]$ServerPath,
[string]$LocalPath = ".",
[Parameter(Mandatory=$True)]
[ValidateSet("Download", "Upload")]
[string]$Action
)
# Executes once before the first pipeline object is processed.
Begin {
# We'll be working with .NET classes, so set the .NET working folder to ours
# to make relative paths behave as expected in uploads and downloads.
[System.IO.Directory]::SetCurrentDirectory(((Get-Location -PSProvider FileSystem).ProviderPath))
$webclient = New-Object System.Net.WebClient
$webclient.Credentials = New-Object System.Net.NetworkCredential($UserName, $Password)
}
# Executes once per pipeline object.
Process {
switch ($Action) {
"Download" { $webclient.DownloadFile("$ServerPath/$FileName", "$LocalPath/$FileName") }
"Upload" { $webclient.UploadFile("$ServerPath/$FileName", "$LocalPath/$FileName") }
}
}
# Executes once after the last pipeline object is processed.
End {
# Nothing to clean up. No need to Dispose() the WebClient.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment