简体   繁体   中英

Detecting PowerShell script is executed with error

I have a PowerShell script:

...
Any-Command -ErrorCode Stop
...

Then I call this script from a bat script:

...
powershell myscript.ps1
...

Now I would like to know in the bat script if the called PowerShell script is stopped on error and not reached the end of the script. How to do it?

One way to do it would be to add a top level trap statement to your script, something like:

trap {
   exit 1; # or whatever error code
}

Note: trap may be considered old fashioned (although I like it top-level), the other option would be a try-finally around your whole script.

So when Any-Command exits with an exception, the trap statement is executed and the script exits with error code 1. If you don't add this, Powershell will exit with error code 0 (after all Powershell ran just fine, although the script didn't).

You can then detect the error code in a bat script using something like:

powershell -noprofile -noninteractive -file <<your script>>

IF ERRORLEVEL 1 (echo ERROR) ELSE (echo OK)

pause

This will detect any error code of 1 or higher.

You can also use %ERRORLEVEL% but be wary that this may be overridden as an environment variable.

Note: if you're running your script in a nested runspace, you could consider using $host.SetShouldExit(1) to ensure the root host exits as well.

Just adding to the answer given by Marcus

I noticed that the trap code even hides the actual error. In my case I needed the actual error occurred. Just adding the modified code for the completion.

 trap 
    { 
        write-error $("Error: " + $_.Exception.Message); 
        exit 1; # or whatever error code 
    } 

More info at http://huddledmasses.org/trap-exception-in-powershell/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM