【问题标题】:WebClient downloadfileWebClient 下载文件
【发布时间】: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


【解决方案1】:

您使用哪个 PowerShell 版本?有人报告System.Net.WebClient.DownloadFile 在带有 PowerShell 4.0 的 Windows 2012 Server 上完美运行,但在 Windows 8 上抛出异常。

因此,出于文件下载目的,您可以尝试Invoke-WebRequest cmdlet:

Invoke-WebRequest $fileURL -OutFile $target  

【讨论】:

    猜你喜欢
    • 2019-01-28
    • 1970-01-01
    • 1970-01-01
    • 2014-06-20
    • 2012-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多