WebClient downloadfile

别说谁变了你拦得住时间么 提交于 2019-12-20 02:42:16

问题


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:

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

The Write-Host $newTarget value looks like this:

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

回答1:


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.

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

Invoke-WebRequest $fileURL -OutFile $target  


来源:https://stackoverflow.com/questions/32907484/webclient-downloadfile

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!