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
}