3

I want to run a PowerShell command (not script) from a cmd.exe and manage the exit code properly:

powershell.exe [bool]((get-service wsearch).status -eq 'Running')

But I would like to return the boolean status as the error level.

I would like to echo %errorlevel% after running it and use it to determine service status.

2 Answers 2

3

Just use the PowerShell exit command providing the result as an argument. For example:

C:\>powershell -command "exit [int]$true;"

C:\>echo %errorlevel%
1

C:\>powershell -command "exit [int]$false;"

C:\>echo %errorlevel%
0

Or for your case:

powershell.exe -command "exit [int]((get-service wsearch).status -eq 'Running')"
Sign up to request clarification or add additional context in comments.

3 Comments

What if the command fails for some reason? Then the exit code is also 1 and this does not mean "the command has worked and exited with the code 1". With this approach consider at least to exit with some different code.
@RomanKuzmin It still works for me even if the command fails. Presumably because exit is getting the result of the boolean test operator, not the command itself.
Maybe, on not terminating errors (and correctness of the result is still not clear). But in cases of terminating errors exit is not invoked, instead PowerShell should exit itself with 1.
0

You can also use this variant:

CMD I> Set cmd=powershell -c "((gsv wsearch -ea 0).status -eq 'Running')"
CMD I> %cmd% |>nul find "True" && echo RUNNING||echo NOT RUNNING
RUNNING

CMD I> Set cmd=powershell -c "((gsv youka -ea 0).status -eq 'Running')"
CMD I> %cmd% |>nul find "True" && echo RUNNING||echo NOT RUNNING
NOT RUNNING

Comments

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.