Question:
I’m using a power shell script to copy some files from my computer to a USB drive. However, even though I’m catching the System.IO exception, I still get the error at the bottom. How do I properly catch this exception, so it shows the message in my Catch block.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
CLS $parentDirectory="C:\Users\someUser" $userDirectory="someUserDirectory" $copyDrive="E:" $folderName="Downloads" $date = Get-Date $dateDay=$date.Day $dateMonth=$date.Month $dateYear=$date.Year $folderDate=$dateDay.ToString()+"-"+$dateMonth.ToString()+"-"+$dateYear.ToString(); Try{ New-Item -Path $copyDrive\$folderDate -ItemType directory Copy-Item $parentDirectory\$userDirectory\$folderName\* $copyDrive\$folderDate } Catch [System.IO] { WriteOutput "Directory Exists Already" } New-Item : Item with specified name E:\16-12-2014 already exists. At C:\Users\someUser\Desktop\checkexist.ps1:15 char:9 + New-Item -Path $copyDrive\$folderDate -ItemType directory + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ResourceExists: (E:\16-12-2014:String) [New-Item], IOException + FullyQualifiedErrorId : DirectoryExist,Microsoft.PowerShell.Commands.NewItemCommand |
Answer:
I don’t suggest actually catching the error in this case. Although that may be the correct action in general, in this specific case I would do the following:
1 2 3 4 5 6 7 8 9 |
$newFolder = "$copyDrive\$folderDate" if (-not (Test-Path $newFolder)) { New-Item -Path $newFolder -ItemType directory Copy-Item $parentDirectory\$userDirectory\$folderName\* $newFolder } else { Write-Output "Directory Exists Already" } |