PowerShell:System.Net.WebClient.DownloadFile 不会下载从 ListDirectory 收集的文件

PowerShell: System.Net.WebClient.DownloadFile won't download files collected from ListDirectory

我正在尝试从 FTP 服务器下载一些 zip 文件。 FTP 服务器的结构如下

ftp://ftp.example.com
|
 -> /Download
    | 
     -> file1.zip, file2.zip, file3.zip etc

我已将所有文件提取到一个名为 $ftpFiles

的数组中
foreach ($zip in $ftpFiles)
{
    $LocalFile = "C:\Temp$zip"
    $RemoteFile = "$site/$zip"
    $ftp = New-Object System.Net.WebClient
    $ftp.Credentials = new-object System.Net.NetworkCredential($Username, $realPassword)
    $uri = New-Object System.Uri("$RemoteFile")
    $ftp.DownloadFile($uri, $LocalFile)
    Write-Host "$zip download complete"
}

问题是 $ftp.DownloadFile 不适用于我的 $LocalFile 变量。但是,如果我手动输入 $LocalFile 信息,它会。

例如

$ftp.DownloadFile($uri, "C:\temp\file1.zip")

工作正常,但是

$ftp.DownloadFile($uri, $LocalFile)

给我以下错误

Exception calling "DownloadFile" with "2" argument(s): "An exception occurred during a WebClient request."
At line:1 char:34
 +                 $ftp.DownloadFile <<<< ($uri, $LocalFile)
 + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
 + FullyQualifiedErrorId : DotNetMethodException

出于调试目的我一直在做

write-host $LocalFile

这将 return 正确地作为

C:\Temp\file1.zip

如我所料。

我只能假设 DownloadFile 不喜欢嵌套变量并将其读取为 C:\Temp$zip,我不确定如何修复它。

编辑:评论想看看$files数组是如何构建的

$site = $ftpbase + $dir

$ftp = [System.Net.FtpWebRequest]::Create("$site")
$ftp.Method = [System.Net.WebRequestMethods+FTP]::ListDirectory #Details
$ftp.Credentials = new-object System.Net.NetworkCredential($Username, $realPassword)

$response = $ftp.getresponse() 
$stream = $response.getresponsestream() 

$buffer = new-object System.Byte[] 1024 
$encoding = new-object System.Text.AsciiEncoding 

$outputBuffer = "" 
$foundMore = $false 

## Read all the data available from the stream, writing it to the 
## output buffer when done. 
do 
{

    ## Allow data to buffer for a bit 
    start-sleep -Seconds 2 

    ## Read what data is available 
    $foundmore = $false 
    $stream.ReadTimeout = 1000

    do 
    { 
        try 
        { 
            $read = $stream.Read($buffer, 0, 1024) 

            if($read -gt 0) 
            { 
                $foundmore = $true 
                $outputBuffer += ($encoding.GetString($buffer, 0, $read))

            } 
        } catch { $foundMore = $false; $read = 0 } 
    } while($read -gt 0) 
} 
while($foundmore)

$files = $outputBuffer -split ("\n")

ListDirectory 的输出为 ASCII 模式,其中行由 \r\n 分隔。您仅按 \n 拆分输出,因此 \r 保留在文件名中。

因此下载失败,因为文件 file1.zip\r 不存在。

当您打印 file1.zip\r 时,您将看不到 \r