简体   繁体   中英

Changing FTP from binary to ascii in PowerShell script using WebClient

Simple PowerShell script. It downloads a file (in binary) with no issues. I need it in ascii.

$File = "c:\temp\ftpfile.txt"
$ftp = "ftp://myusername:mypass@12.345.6.78/'report'";
$webclient = New-Object -TypeName System.Net.WebClient;
$uri = New-Object -TypeName System.Uri -ArgumentList $ftp;
$webclient.DownloadFile($uri, $File);

The WebClient does not support ascii/text FTP mode.

Use FtpWebRequest instead and set .UseBinary to false.

$File = "c:\temp\ftpfile.txt"
$ftp = "ftp://myusername:mypass@12.345.6.78/'report'";

$ftprequest = [System.Net.FtpWebRequest]::Create($ftp)

$ftprequest.Method = [System.Net.WebRequestMethods+Ftp]::DownloadFile
$ftprequest.UseBinary = $false

$ftpresponse = $ftprequest.GetResponse()

$responsestream = $ftpresponse.GetResponseStream()

$targetfile = New-Object IO.FileStream($File, [IO.FileMode]::Create)

$responsestream.CopyTo($targetfile)

$targetfile.close()

Reference: What's the best way to automate secure FTP in PowerShell?


Note that the WebClient uses the FtpWebRequest internally, but does not expose its .UseBinary property.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM