Skip to content

Instantly share code, notes, and snippets.

@JohnLBevan
Created October 27, 2023 16:22
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 JohnLBevan/517802d40186282212425ff69ec0a6d1 to your computer and use it in GitHub Desktop.
Save JohnLBevan/517802d40186282212425ff69ec0a6d1 to your computer and use it in GitHub Desktop.
FTP Upload using PowerShell
Function Copy-FtpItem {
[CmdletBinding()]
Param (
[Parameter(Mandatory, ValueFromPipeline)]
[string[]]$Path
,
[Parameter(Mandatory)]
[string]$FtpHost
,
[Parameter()]
[int]$Port = 21
,
[Parameter(Mandatory)]
[System.Management.Automation.PSCredential]
[System.Management.Automation.Credential()]$Credential
,
[Parameter()]
[string]$Folder = ''
,
[Parameter()]
[Switch]$UseBinary
,
[Parameter()]
[Switch]$UsePassive
)
Process {
# note: assume it negotiates TLS, rather than requiring implicit FTPS://..
$ftpUriRoot = "ftp://$($FtpHost):$($Port)/$($Folder.Trim('[/\\]'))"
foreach ($file in $Path) {
$fn = Split-Path -Path $file -Leaf
$uri = '{0}/{1}' -f $ftpUriRoot, $fn
$ftp = [System.Net.FtpWebRequest]::Create($uri) # could alternatively use [System.Net.WebRequest] and have it implicitly convert
$ftp.Credentials = $Credential
$ftp.Method = [System.Net.WebRequestMethods+Ftp]::UploadFile
$ftp.UseBinary = $UseBinary.IsPresent
$ftp.UsePassive = $UsePassive.IsPresent
try {
$fs = [System.IO.File]::OpenRead($file)
$ftps = $ftp.GetRequestStream()
$fs.CopyTo($ftps)
} finally {
if ($null -ne $ftps) {$ftps.Dispose(); $ftps = $null}
if ($null -ne $fs) {$fs.Dispose(); $fs = $null}
}
}
}
}
$creddyMurphy = [System.Management.Automation.PSCredential]::new('abcdef', ('ghijklmn' | ConvertTo-SecureString -AsPlainText -Force))
Copy-FtpItem -Path 'c:\temp\poc.zip' -FtpHost 'ftp.example.com' -Port 21 -Credential $creddyMurphy -Folder 'TargetFolder' -UseBinary -UsePassive -Verbose -ErrorAction Stop
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment