PowerShell WebClient DownloadFile异常:路径中有非法字符

3

我正在尝试从FTP站点下载zip文件,基于检索目录列表以查找文件名。

下载部分:

$folderPath='ftp://11.111.11.11/'
$target = "C:\Scripts\ps\ftpdl\"

Foreach ($file in ($array | where {$_ -like "data.zip"})) {

$Source = $folderPath+$file
$Path = $target+$file

#$Source = "ftp://11.111.11.11/data.zip"
#$Path = "C:\Scripts\ps\ftpdl\data.zip"

$source
Write-Verbose -Message $Source -verbose
$path
Write-Verbose -message $Path -verbose

$U = "User"
$P = "Pass"
$WebClient2 = New-Object System.Net.WebClient
$WebClient2.Credentials = New-Object System.Net.Networkcredential($U, $P)
$WebClient2.DownloadFile( $source, $path )  
}

如果我使用注释并定义字符串,它可以正确下载。但如果按照所示运行,将收到异常错误“路径中存在非法字符”的提示。有趣的是,write-verbose 和未使用 write-verbose 之间存在差异。
按照所示运行后的输出:
ftp://11.111.11.11/data.zip
data.zip
C:\Scripts\ps\ftpdl\data.zip
data.zip
Exception calling "DownloadFile" with "2" .........

在使用硬编码的路径和源代码运行时输出。
ftp://11.111.11.11/data.zip
VERBOSE: ftp://11.111.11.11/data.zip
C:\Scripts\ps\ftpdl\data.zip
VERBOSE: C:\Scripts\ps\ftpdl\data.zip    

文件可以顺利下载。
1个回答

3

当然,一旦我发布了问题,我就解决了它。我的 $array 包含了 `n 和 `r 字符。我需要找到并替换掉它们。

$array=$array -replace "`n",""
$array=$array -replace "`r",""

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接