3

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
}
3
  • 2
    There is no Write-Host $newTarget in your code. You output $newFileName, but you you try to download to $newTarget, which is "$TargetDirectory\$newFileName". Commented Oct 2, 2015 at 13:49
  • If the Root share on NRP-12-62-3 isn't root C:\ like it suggests then you could be hitting a file length ceiling of 255 characters. That whole path is 201 chars so if the share is buried a bit it's possible. Commented Oct 2, 2015 at 14:42
  • Great catch Ansgar. It's all good now. I updated the original code. Commented Oct 2, 2015 at 15:24

1 Answer 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  
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.