PowerShell Script Trap Statement capture exception Writing instance _powershell

Source: Internet
Author: User
Tags try catch

First look at a script file: 3.three.test.ps1

Copy Code code as follows:

Get-fanbingbing #命令不存在

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.