gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 23:25:33 25 4
gpt4 key购买 nike

我正在尝试从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")

最佳答案

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

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

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

关于.net - PowerShell:System.Net.WebClient.DownloadFile不会下载从ListDirectory收集的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37925267/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com