Created
October 27, 2023 16:22
-
-
Save JohnLBevan/517802d40186282212425ff69ec0a6d1 to your computer and use it in GitHub Desktop.
FTP Upload using PowerShell
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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