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

时间:2016-06-20 14:37:20

标签: .net powershell ftp webclient ftpwebrequest

我试图从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

将正确返回

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

1 个答案:

答案 0 :(得分:3)

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

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

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