简体   繁体   中英

WebClient downloadfile

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
}

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  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM