How to get exitcode from Powershell and return to CMD?

Question

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
Solution

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%