Skip to content

Instantly share code, notes, and snippets.

@jborean93
Last active October 19, 2022 00:20
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jborean93/6fe2d87bbf23626b398654fe0a129202 to your computer and use it in GitHub Desktop.
Save jborean93/6fe2d87bbf23626b398654fe0a129202 to your computer and use it in GitHub Desktop.
Gets a file from an FTP(S) server
# Copyright: (c) 2020, Jordan Borean (@jborean93) <jborean93@gmail.com>
# MIT License (see LICENSE or https://opensource.org/licenses/MIT)
Function Get-FtpFile {
[CmdletBinding()]
param (
[Parameter(Mandatory=$true)]
[System.Uri]
[Alias('Uri')]
$FtpUrl,
[Parameter(Mandatory=$true)]
[System.String]
$OutFile,
[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
}
if ($secure) {
$request.EnableSSL = $true
}
if ($Credential) {
$request.Credentials = $Credential
}
$ftpReader = $null
try {
$ftpReader = $request.GetResponse().GetResponseStream()
$outFS = [IO.File]::OpenWrite($OutFile)
try {
$ftpReader.CopyTo($outFS)
} finally {
$outFS.Dispose()
}
} catch {
Write-Error -Message "Failed to download FTP file: $($_.Exception.Message)" -Exception $_.Exception
return
} finally {
if ($ftpReader) {
$ftpReader.Dispose()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment