Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 determine) the exception that is being thrown. Normally I'll just catch System.Exception which is a bad idea.

Here is an example... I'm trying to create a folder on a drive that doesn't 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've tried catching System.DriveNotFoundException, but rerunning my script still produces the uncaught exception.

Are there any tips as to effectively handling any type of exception?

like image 967
hax0r_n_code Avatar asked Oct 01 '13 13:10

hax0r_n_code


People also ask

How do you catch exceptions in PowerShell?

The catch keyword is followed by an optional list of error type specifications and a statement list. If a terminating error occurs in the try block, PowerShell searches for an appropriate catch block. If one is found, the statements in the catch block are executed. The catch block can specify one or more error types.

How do you catch exceptions?

The try-catch is the simplest method of handling exceptions. Put the code you want to run in the try block, and any Java exceptions that the code throws are caught by one or more catch blocks. This method will catch any type of Java exceptions that get thrown. This is the simplest mechanism for handling exceptions.

How do you catch non-terminating errors in PowerShell?

The above error is generated by cmdlet and it is a non-terminating error. You can handle both the terminating and non-terminating error (by converting them into terminating error) using ErrorAction cmdlet, $ErrorActionPreference variable and try, catch, and finally blocks.

What is $_ in PowerShell?

The “$_” is said to be the pipeline variable in PowerShell. The “$_” variable is an alias to PowerShell's automatic variable named “$PSItem“. It has multiple use cases such as filtering an item or referring to any specific object.


1 Answers

Right after running the command inspect the contents of $error[0]. Look at the Exception property e.g.:

$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

That particular exception would be [System.Management.Automation.DriveNotFoundException].

BTW if you want to "catch" that exception, you will need to convert the non-terminating error into a terminating error using -EA Stop in order for it to generate an exception that you can catch e.g.:

PS> try {mkdir z:\foo -ea Stop} catch {$_.Exception.GetType().FUllname}
System.Management.Automation.DriveNotFoundException
like image 139
Keith Hill Avatar answered Oct 29 '22 16:10

Keith Hill