Changing FTP from binary to ascii in PowerShell sc

2019-06-14 09:36发布

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);

1条回答
劫难
2楼-- · 2019-06-14 10:21

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)
[byte[]]$readbuffer = New-Object byte[] 1024

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

$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.

查看更多
登录 后发表回答