使用WebClient在PowerShell脚本中将FTP从二进制更改为ascii

时间:2015-06-19 20:32:59

标签: powershell ftp webclient

简单的PowerShell脚本。它下载文件(二进制)没有问题。我需要它在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 个答案:

答案 0 :(得分:0)

WebClient不支持ascii / text FTP模式。

改为使用FtpWebRequest并将.UseBinary设为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()

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

请注意,WebClient在内部使用FtpWebRequest,但不会公开其.UseBinary属性。