我有以下PS脚本,用于使用WebClient下载文件。下载链接在文本文件中。下载正常工作,但我想确保不覆盖重复的文件,所以我添加了额外的代码。该代码对单个文件运行良好。然而,如果发现重复,则代码会出错,并显示以下错误信息:“调用“DownloadFile”时出错,带有“2”个参数:在WebClient请求期间发生异常。” $newTarget的值看起来像这样:“\\NRP-12-62-3\Root\NV-RST\Southwest Projects\Marketing Analysis\Monthly Sales Reports\10-01-2015-223403\Travis, Martin_17Jul14 17.42.45_Nature Mountain Daily Update 07-17-14.docx - duplicate 223541.msg”。
$docLinkFile = "c:\temp\urls.csv"
$webclient = New-Object System.Net.WebClient
$webclient.Credentials = $cred
$TargetDirectory = "\\NRP-12-62-3\Root\NV-RST\Southwest Projects\Marketing Analysis\Monthly Sales Reports"
$subDirectoryName = $((Get-Date).ToString('MM-dd-yyyy-HHmmss'))
$TargetDirectory = $TargetDirectory + "\" + $subDirectoryName
# Create directory
$subDirectory = New-Item -ItemType directory -Path $TargetDirectory
foreach ($i in Import-Csv $docLinkFile) {
$fileURL = $i.DOC_URL
Write-Host $fileURL
$splitByslash = $fileURL.Split("/")
# return the last element of the array
$fileName = $splitByslash[-1]
Write-Host $fileName -ForegroundColor Green
$target = $TargetDirectory + "\" + $fileName
if (Test-Path $target) {
$existingFileName = [io.path]::GetFileNameWithoutExtension($target)
$extension = [io.path]::GetExtension($target)
$newFileName = "$TargetDirectory" +"\" + $existingFileName + " - duplicate $(get-date -f HHmmss)" + "" + $extension
Write-Host $newFileName
$webclient.DownloadFile($fileURL, $newFileName)
} else {
$webclient.DownloadFile($fileURL, $target)
}
Start-Sleep -s 1
}
Write-Host $newTarget
。你输出了$newFileName
,但是你尝试下载到$newTarget
,它是"$TargetDirectory\$newFileName"
。 - Ansgar WiechersNRP-12-62-3
上的Root
共享不是像建议的那样的根目录C:\,那么您可能会遇到255个字符的文件长度限制。整个路径有201个字符,所以如果共享被埋藏了一点,这是有可能的。 - Deadly-Bagel