简体   繁体   中英

Handling a powershell error into a batch file

I have powershell code that is similar to this:

If ($a -eq $false)
{
    "FALSE"
    exit 5
}
Else
{
    If ($b -eq $false)
    {
        "FALSE"
        exit 5
    }
}

I have imported this code into a batch file with the powershell -Command "& { }" command and I want my rest batch code to continue only in the case that the powershell command didn't returned an error($a or $b was false).

So far, I tried many things like this but they instantly close my batch file:

@echo off
`some batch code here`
powershell -Command "& { }"
echo %errorlevel%
if '%errorlevel%' NEQ '5'
{
    `code here`
}
echo ERROR
pause
exit

The best way for me to do it, would be if I could exit powershell's "if" block with code "5" for example and put an if statement in batch that checks if the error is 5. The echo %errorlevel% prints "5" in that case but seems like the if statement doesn't work.

In PowerShell return an Integer when you exit:

Exit 0

or

Exit 25

in your batch file run the PowerShell script like this:

powershell -Command "& {C:\scripts\myscript.ps1; exit $lastexitcode}"

now PowerShell will return the exit code from the script to the calling batch file where you can use it:

echo %errorlevel%
@echo off
`some batch code here`
powershell -Command "& { if $a -eq $false -or $b -eq $false { 'FALSE'; exit 5} }"
echo %errorlevel%
if '%errorlevel%' NEQ '5' (
    `code here`
)
echo ERROR
pause
exit

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM