【发布时间】:2015-12-30 16:22:56
【问题描述】:
我有以下 PS 脚本来使用 WebClient 下载文件。下载链接位于文本文件中。下载工作,但是,我想确保我不会覆盖重复的文件,所以我添加了额外的代码。该代码对单个文件运行良好。但是,如果发现重复,则代码会因以下错误而中断:
使用“2”个参数调用“DownloadFile”的异常:“WebClient 请求期间发生异常。”
Write-Host $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 每日更新 07-17- 14.docx - 重复 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"。 -
如果
NRP-12-62-3上的Root共享不是根 C:\ 就像它所暗示的那样,那么您可能会达到 255 个字符的文件长度上限。整个路径是 201 个字符,所以如果共享部分被掩埋,它是可能的。 -
安斯加尔大获成功。现在一切都好。我更新了原始代码。
标签: powershell webclient webclient-download