When calling a powershell script from a batch file, and exiting with a value, errorlevel is 0 in batch file, not the exit value
I've tried using the code below to call a powershell script which exits with a number that should be an errorlevel in the batch file, but when I check %errorlevel% in the batch file, it is always zero. I'm calling it in the For loop as I need to also have it return some text.
This is the powershell script:
# TestReturnValAndCode.ps1
$DataIn = $args[0]
$ReturnVal="You passed in the text '" + $DataIn + "'"
$ReturnVal
exit 1234
This is the batch file:
:: testpscaller.bat
@echo off
set "BaseFolder=C:\temp\test"
set "TestPSScript=%BaseFolder%\TestReturnValAndCode.ps1"
set "TestValue=Test This Text"
for /f "delims=" %%a in ('powershell -executionpolicy bypass -file
"%TestPSScript%" "TestValue"') do set "ReturnVal=%%a"
@echo ErrorLevel=[%ErrorLevel%]
@echo ReturnVal=[%ReturnVal%]
This is the result:
ErrorLevel=[0] ReturnVal=[You passed in the text 'TestValue']
THe ErrorLevel should be 1234.
What do I need to do to get both my text value and the error level (that is not too klunky/kludgy)