First look at a script file: 3.three.test.ps1
Copy Code code as follows:
Then capture this:
Copy Code code as follows:
Trap [Exception]
{
' Caught a script exception in trap '
$_. Exception.Message
Continue
}
. \3.three.test.ps1
Exception capture succeeded, output:
Copy Code code as follows:
Caught a script exception in the trap
The term ' get-fanbingbing ' is not recognized as the name of a cmdlet
Next I change the contents of the 3.three.test.ps1 script file to:
Copy Code code as follows:
Dir D:\ShenMaDoushiFuYun #目录不存在
To run again, no exception was caught, and the error was: Dir:cannot find path ' D:\ShenMaDoushiFuYun ' because it does not exist.
So I wondered if it was because of the difference between terminating and terminating errors: You wrote a try Catch capture statement, two-pronged:
Copy Code code as follows:
Trap [Exception]
{
' Caught a script exception in trap '
$_. Exception.Message
Continue
}
try{
. \3.three.test.ps1
}
catch{
' Caught in a catch with a script exception '
$_. Exception.Message
}
Exception still: Dir:cannot find path ' D:\ShenMaDoushiFuYun ' because it does not exist.
It seems that the problem is not here. In fact, it's a question of erroractionreference, so change is OK:
Copy Code code as follows:
Trap [Exception]
{
' Caught a script exception in trap '
$_. Exception.Message
Continue
}
$ErrorActionPreference = ' Stop '
. \3.three.test.ps1
The output is:
Copy Code code as follows:
Caught a script exception in the trap
Cannot find path ' D:\ShenMaDoushiFuYun ' because it does not exist.
Simple analysis:
The exception, like Get-fanbingbing, is because the command does not exist, in the exact case of grammatical errors, higher levels are trapped. However, a directory that cannot find such an exception is relatively low-level and cannot be caught by default unless the display specifies erroraction as stop.