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

Changing FTP from binary to ascii in PowerShell script using 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);

WebClient不支持ascii/textFTP模式

使用FtpWebRequest instead and set .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)

$responsestream.CopyTo($targetfile)

$targetfile.close()

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


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