Skip to content

Instantly share code, notes, and snippets.

@jborean93
Created December 2, 2022 03:20
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 jborean93/ff5a1e02963c5023fb6489bf0e8c4b00 to your computer and use it in GitHub Desktop.
Save jborean93/ff5a1e02963c5023fb6489bf0e8c4b00 to your computer and use it in GitHub Desktop.
Copies a file to an FTP(S) server
# Copyright: (c) 2022, Jordan Borean (@jborean93) <jborean93@gmail.com>
# 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