Last active
October 19, 2022 00:20
-
-
Save jborean93/6fe2d87bbf23626b398654fe0a129202 to your computer and use it in GitHub Desktop.
Gets a file from an FTP(S) server
This file contains 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) 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