WebClient下载文件

3
我有以下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
}

2
你的代码中没有 Write-Host $newTarget。你输出了 $newFileName,但是你尝试下载到 $newTarget,它是 "$TargetDirectory\$newFileName" - Ansgar Wiechers
如果NRP-12-62-3上的Root共享不是像建议的那样的根目录C:\,那么您可能会遇到255个字符的文件长度限制。整个路径有201个字符,所以如果共享被埋藏了一点,这是有可能的。 - Deadly-Bagel
很好的发现,Ansgar。现在一切都好了。我更新了原始代码。 - Ninja Cowgirl
1个回答

1
你使用哪个PowerShell版本?一些人报告说在Windows 2012 Server上使用PowerShell 4.0的System.Net.WebClient.DownloadFile非常完美,但在Windows 8上会抛出异常。因此,为了文件下载的目的,您可以尝试使用Invoke-WebRequest cmdlet。
Invoke-WebRequest $fileURL -OutFile $target  

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