Created
December 2, 2022 03:20
-
-
Save jborean93/ff5a1e02963c5023fb6489bf0e8c4b00 to your computer and use it in GitHub Desktop.
Copies a file to an FTP(S) server
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
# Copyright: (c) 2022, Jordan Borean (@jborean93) <[email protected]> | |
# MIT License (see LICENSE or https://opensource.org/licenses/MIT) | |
Function Copy-ToFtp { | |
[CmdletBinding()] | |
param ( | |
[Parameter(Mandatory = $true)] | |
[System.String] | |
$Path, | |
[Parameter(Mandatory = $true)] | |
[System.Uri] | |
[Alias('Uri')] | |
$FtpUrl, | |
[PSCredential] | |
$Credential | |
) | |
$secure = $false | |
if ($FtpUrl.Scheme -eq 'ftps') { | |
$secure = $true | |
$FtpUrl = [uri]('ftp' + ($FtpUrl.ToString().Substring(4))) | |
} | |
$request = [System.Net.WebRequest]::Create($FtpUrl) | |
if (-not $request -is [System.Net.FtpWebRequest]) { | |
Write-Error -Message "FtpUrl is not a valid FTP address starting with ftp://" | |
return | |
} | |
$request.Method = [System.Net.WebRequestMethods+Ftp]::UploadFile | |
if ($secure) { | |
$request.EnableSSL = $true | |
} | |
if ($Credential) { | |
$request.Credentials = $Credential | |
} | |
$ftpWriter = $null | |
try { | |
$ftpWriter = $request.GetRequestStream() | |
$outFS = [System.IO.File]::OpenRead($Path) | |
try { | |
$outFS.CopyTo($ftpWriter) | |
} | |
finally { | |
$outFS.Dispose() | |
} | |
} | |
catch { | |
Write-Error -Message "Failed to upload file to FTP: $($_.Exception.Message)" -Exception $_.Exception | |
return | |
} | |
finally { | |
if ($ftpWriter) { | |
$ftpWriter.Dispose() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment