Powershell Try Catch IOException DirectoryExist

I use a script power shell to copy some files from my computer to a USB drive. However, even though I am catching the System.IO exception, I still get the error below. How do I correctly catch this exception, so it shows the message in my Catch block.

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
+4
source share
3 answers

I do not suggest actually catching the error in this case. Although this may be the right action in general, in this particular case I would do the following:

$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"
}
0
source

If you want to catch an exception for a call New-Item, you need to do two things:

  • $ErrorActionPreference = "Stop" , Continue. script Stop .

  • /

, catch :

catch 
{
    Write-Output "Directory Exists Already"
}

, , ,

$error[0].Exception.GetType().FullName

:

System.IO.IOException

catch, :

catch [System.IO.IOException]
{
    Write-Output "Directory Exists Already"
}

, : Powershell

+1

-ErrorAction Stop , , [System.IO.IOException] (not [System.IO]). , :

try {
   New-Item -Path $copyDrive\$folderDate -ItemType directory -ErrorAction Stop
   Copy-Item $parentDirectory\$userDirectory\$folderName\* $copyDrive\$folderDate -ErrorAction Stop
}

catch [System.IO.IOException] {
   WriteOutput $_.Exception.Message
}

catch {
   #some other error
}
0

All Articles