5

I have a powershell script. I run my powershell script using a CMD file. I want to get the exit code from my powershell script and return the value to the CMD. I tried this. but it does not return the exitcode, when I execute the CMD file to call the powershell.

PowerShell Script

$SN = "17A1"
$BID = "#SBCM#DBCM"
$FB = "UdpdqfP.Bd"

$SN2 = Get-Content .\out4 | Where-Object{$_.Contains("$SN")}

if($SN2)
{
    Write-Host "OK"
}
else{
    Write-Host "Not ok"
   $ExitCode = "ExitCode"
   $ExitCode = "123"
   Exit $ExitCode
}

CMD to call the powershell and return the exitcode

powershell.exe -ExecutionPolicy Bypass -File %~dp0\test.ps1
ECHO %ExitCode%
Exit /b %ExitCode%

I execute the CMD file, and return this:

D:\XX\>powershell.exe -ExecutionPolicy Bypass -File D:\XX\\test.ps1
Not ok

D:\XX\>ECHO
ECHO is on.

D:\XX\>Exit /b

My expectation once I execute the CMD file:

D:\Boot_Order>powershell.exe -ExecutionPolicy Bypass -File D:\Boot_Order\\test.ps1
Not ok

D:\Boot_Order>ECHO
123

D:\Boot_Order>Exit /b 123
1
  • A clear methodology to handle exit codes in PowerShell and cmd is not straightforward. weblogs.asp.net/soever/… Commented Nov 13, 2019 at 14:16

1 Answer 1

1

Batch files work with the environment variable %errorlevel% so change the batch file to:

powershell.exe -ExecutionPolicy Bypass -File "%~dp0\test.ps1"
echo %errorlevel%
exit /b %errorlevel%
Sign up to request clarification or add additional context in comments.

2 Comments

This does not work as expected. Tried this with test.ps1 having exit 10 but errorlevel ending up as 1. DOS is made as useless as possible
Is there any other command between the echo and exit line in your script, @gk_2000

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.