2

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?

1
  • 1
    Is %ERRORLEVEL% set? Does using return ‹n› at the end of the PowerShell with ‹n› > 0 help? Commented Nov 18, 2012 at 17:57

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.