Reputation: 505
I want to run the script from command line, and get the error level. I use this batch script.
set log=C:\Users\PowerShell\XML\Log.txt
set PS=C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
set PS=%PS%\powershell.exe
"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" C:\Users\XML.ps1 -i C:\Users\A2.txt -j C:\Users\Fb.xml
echo %ERRORLEVEL% > "%log%"
I tried this script to get the custom errorlevel, If it is found, it will return 123
, otherwise 456
. But It always gives me 1
.
$regex = [regex]$Pattern
$matching = $regex.Match($FBString)
if ($matching.Success) {
while ($matching.Success) {
"Match found: {0}" -f $matching.Value
Exit 123
$matching = $matching.NextMatch()
}
}
else {
"Not Found"
Exit 456
}
Upvotes: 2
Views: 6071
Reputation: 505
The problem is in the batch file. It should be like this :
set log=C:\Users\PowerShell\XML\Log.txt
# Note the use of -File
"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -ExecutionPolicy Bypass -File C:\Users\XML.ps1 -i C:\Users\A2.txt -j C:\Users\Fb.xml
echo %ERRORLEVEL% > "%log%"
For the first PowerShell script is correct already.
Upvotes: 1
Reputation: 3193
You can write the logic in your script
so any exit point will set the %errorlevel%
system variable...
and create your "error return logic"...
something lihe this:
if ( $LASTEXITCODE -eq 0 ) { exit 0 }
if ( $LASTEXITCODE -eq 1 ) { exit 1 }
if ( $x -gt 1 ) { exit 2 }
if ( $x -lt 1 ) { exit 3 }
...
and then you can inspect from a batch file for %errorlevel% == 0
, 1
, 2
, ...
Upvotes: 2
Reputation: 27408
Run the script with powershell -file. The default is powershell -command. Once that script is over, with -command the session is still going.
Upvotes: 1
Reputation: 9123
Change the Exit
to Return
. Exit will exit your script. Return will return values that you wish for.
Upvotes: 2