PowerShell does not come with cmdlets to download and upload data via FTP. However, you can use .NET for this.

To download a file from an FTP server in binary mode, try the code below which also illustrates how you can authenticate with explicit credentials:

$username='testuser'
$password='[email protected]'
[System.Uri]$uri='ftp://192.168.1.123/test.txt'

$localFile = 'C:\test.txt'

$ftprequest=[System.Net.FtpWebRequest]::Create($uri)
$ftprequest.Credentials=[System.Net.NetworkCredential]::new($username,$password)
$ftprequest.Method=[System.Net.WebRequestMethods+Ftp]::DownloadFile
$ftprequest.UseBinary = $true
$ftprequest.KeepAlive = $false
$response=$ftprequest.GetResponse()
$stream=$response.GetResponseStream()

try
{
    $targetfile = [System.IO.FileStream]::($localFile,[IO.FileMode]::Create)
    [byte[]]$readbuffer = New-Object byte[] 1024

    do{
        $readlength = $stream.Read($readbuffer,0,1024)
        $targetfile.Write($readbuffer,0,$readlength)
    }
    while ($readlength -gt 0)

    $targetfile.Close()
}
catch
{
    Write-Warning "Error occurred: $_"
}




Twitter This Tip! ReTweet this Tip!

Anonymous