1

Powershell does not set ERRORLEVEL variable on an ExecutionPolicy error.
So how can one determine in batch code that the script has failed?

C:\Windows\system32>powershell -File myScript.ps1  
Attempting to perform the InitializeDefaultDrives operation on the 'FileSystem' provider failed.  
File myScript.ps1 cannot be loaded. The file myScript.ps1 is not digitally signed. You cannot run this script on the current system.  
For more information about running scripts and setting execution policy, see about_Execution_Policies at
http://go.microsoft.com/fwlink/?LinkID=135170.
+ CategoryInfo          : SecurityError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : UnauthorizedAccess

C:\Windows\system32>echo %ERRORLEVEL%  
0
2
  • The only way I can think of doing it involves wrapping the script invocation in a broader command with try / catch and pushing exit SomeNum in the catch block. Commented Aug 18, 2016 at 8:11
  • As previous comment, you may use something as if ($some-var -eq 'true') {exit 0} else {exit 1}; Commented Aug 18, 2016 at 8:15

2 Answers 2

2

At the bottom you can put something like:

if (-not $?) { exit 1 }

Or

exit $error.count

If you're willing to use -erroraction stop, to create a script-terminating exception, that would set the errorlevel from a script:

# foo2 doesn't exist
get-childitem foo2 -erroraction stop

Also, this one liner from cmd will set the errorlevel, even with a non-terminating exception:

powershell get-childitem foo2 # there is no foo2
Sign up to request clarification or add additional context in comments.

Comments

-2
set NLS_LANG=American_America.AL32UTF8

REM your code

echo %ERRORLEVEL%

This is a simple batch file. %ERRORLEVEL% will display error in the prompt

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.