How to catch exceptions in powershell?

If I have a piece of code that throws an exception, I get an error message, but I have no idea how to correctly catch (or define) the exception to be thrown. I usually just catch System.Exceptionthat bad idea.

Here is an example ... I am trying to create a folder on a disk that does not exist:

PS <dir> .\myScript.ps1 z:\test
mkdir : Cannot find drive. A drive with the name 'z' does not exist.
At <dir>myScript.ps1:218 char:7
+       mkdir $args[0] 1> $null
+       ~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (z:String) [New-Item], DriveNotFoundExc 
   eption
    + FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.NewItemComm 
   and

I tried catching System.DriveNotFoundException, but reusing my script still raises an uncaught exception.

Are there any tips for dealing effectively with any type of exception?

+4
source share
1 answer

Immediately after starting, the command checks the contents of $ error [0]. Look at the Exception property, for example:

$error[0] | fl * -force

writeErrorStream      : True
PSMessageDetails      :
Exception             : System.Management.Automation.DriveNotFoundException: Cannot find drive. A drive with the name
                        'z' does not exist.
                           at System.Management.Automation.SessionStateInternal.GetDrive(String name, Boolean
                        automount)
                           at System.Management.Automation.SessionStateInternal.GetDrive(String name, Boolean

[System.Management.Automation.DriveNotFoundException].

, "" , -EA Stop, , , :

PS> try {mkdir z:\foo -ea Stop} catch {$_.Exception.GetType().FUllname}
System.Management.Automation.DriveNotFoundException
+4

All Articles