alexey
alexey

Reputation: 8480

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?

Upvotes: 2

Views: 1276

Answers (2)

isuru chathuranga
isuru chathuranga

Reputation: 1015

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/

Upvotes: 0

Marcus
Marcus

Reputation: 6107

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.

Upvotes: 4

Related Questions