SoFunction
Updated on 2025-04-08

Powershell tips: Capture exceptions inside scripts

First look at a script file: .ps1

Copy the codeThe code is as follows:

Get-FanBingbing #Command does not exist

Then capture it like this:

Copy the codeThe code is as follows:

trap [exception]
{
'Catch script exception in trap'
 $_.
 continue
}
.\.ps1

Exception capture is successful, output:

Copy the codeThe code is as follows:

Catch script exception in trap
The term 'Get-FanBingbing' is not recognized as the name of a cmdlet

Next I change the content of the .ps1 script file to:

Copy the codeThe code is as follows:

dir D:\ShenMaDoushiFuYun #Directory does not exist

Run again, no exception was caught at this time, and the error is: dir: Cannot find path 'D:\ShenMaDoushiFuYun' because it does not exist.

So I wondered if it was because of the difference between termination error and non-termination error: So I also wrote a try catch capture statement, taking two-pronged approach:

Copy the codeThe code is as follows:

trap [exception]
{
'Catch script exception in trap'
 $_.
 continue
}
try{
.\.ps1
}
catch{
'Catch script exception in catch'
 $_.
}

Exception remains: dir : Cannot find path 'D:\ShenMaDoushiFuYun' because it does not exist.

It seems that the problem is not here. In fact, it is an ErrorActionReference problem, so it will be OK to change it:

Copy the codeThe code is as follows:

trap [exception]
{
'Catch script exception in trap'
 $_.
 continue
}
$ErrorActionPreference='stop'
.\.ps1

The output is:

Copy the codeThe code is as follows:

Catch script exception in trap
Cannot find path 'D:\ShenMaDoushiFuYun' because it does not exist.

Simple analysis:

Exceptions like Get-FanBingbing are because the command does not exist. To be precise, they are syntax errors and are trapped at a relatively high level. However, exceptions like those that cannot be found in the directory are relatively low and cannot be caught by default unless the specified ErrorAction is displayed as stop.