WebClient下载文件 [英] WebClient downloadfile

查看:75
本文介绍了WebClient下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下PS脚本使用WebClient下载文件.下载链接位于文本文件中.下载工作正常,但是,我想确保我不会覆盖重复的文件,所以我添加了其他代码.该代码对于单个文件运行良好.但是,如果找到重复项,则代码会因以下错误而中断:

I have following PS script to download file using WebClient. The download links are in a text file. The download works, however, I want to make sure I don't overwrite duplicate files so I added additional code. The code runs good for single file. However, if duplicate is found then the code breaks with this error:

使用"2"作为参数调用"DownloadFile"的异常:在WebClient请求期间发生异常."

Exception calling "DownloadFile" with "2" argument(s): "An exception occurred during a WebClient request."

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 Daily Update 07-17- 14.docx-重复223541.msg

\\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
}

推荐答案

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

Which PowerShell version do you use? Some people report that System.Net.WebClient.DownloadFile works perfectly on Windows 2012 Server with PowerShell 4.0 but throws exception on Windows 8.

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

So, for file download purpose you may try Invoke-WebRequest cmdlet:

Invoke-WebRequest $fileURL -OutFile $target  

这篇关于WebClient下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆