Working cmd command not executing correctly when called via cmd.exe /C

I am trying to execute a one line command including a for loop by calling it via cmd /C.

The command itself executes a forloop to check if a service is running (in this case JBoss) and exits with an error code if it is stopped:

 for /f "tokens=3 delims=: " %H in ('sc query JBossEAP7 ^| findstr "STATE"') do if "%H"=="STOPPED" exit /B 1

This works fine if I enter it in a cmd window or use it in a .bat file (if I substitute % for %%).

However, if I try to call it using cmd /C (like this

cmd /C for /f "tokens=3 delims=: " %H in ('sc query JBossEAP7 ^| findstr "STATE"') do if "%H"=="STOPPED" exit /B 1

I get the error | was unexpected at this time.

Can anyone point me towards a way how I can call this via cmd without using a batch file?

Answer

You can use cmd /c " commands " in your command:

cmd /C "for /f "tokens=3 delims=: " %H in ('sc query JBossEAP7 ^| findstr "STATE"') do if "%H"=="STOPPED" exit /B 1"

Or, in your for loop command "sc query JBossEAP7 | findstr "STATE"":

cmd /C for /f "tokens=3 delims=: " %H in ('"sc query JBossEAP7 | findstr "STATE""') do if "%H"=="STOPPED" exit /B 1

  • You can also use another option to do the same using operator &&:
cmd /c sc query JBossEAP7 | findstr STATE.*STOPPED && exit /b 1

cmd /c "sc query JBossEAP7 | findstr STATE.*STOPPED && exit /b 1"

cmd/csc query JBossEAP7|findstr STATE.*STOPPED&&exit /b 1"

cmd/c|(sc query JBossEAP7 | find "STOPPED" && exit/b 1)

cmd/c| sc query JBossEAP7 | find "STOPPED" && exit/b 1

cmd/c"sc query JBossEAP7|find "STOPPED"&&exit/b 1"

cmd/c|sc query JBossEAP7|find "STOPPED"&&exit/b 1

Obs.: The command findstr STATE.*STOPPED will find in the same line where you have:

rem :: STATE + One_or_More_Characters + STOPPED
> sc query vds
SERVICE_NAME: vds
        TYPE               : 10  WIN32_OWN_PROCESS
        STATE              : 1  STOPPED
        WIN32_EXIT_CODE    : 1077  (0x435)
        SERVICE_EXIT_CODE  : 0  (0x0)
        CHECKPOINT         : 0x0
        WAIT_HINT          : 0x0

> sc query vds | findstr STATE.*STOPPED
        STATE              : 1  STOPPED

             |----------------------| 
 
        STATE +        .*       + STOPPED

rem :: Omitting output >nul and using end End Of Line in findstr /e STOPPED
> sc query vds | findstr /e STOPPED>nul 
        STATE              : 1  STOPPED


How does the Windows Command Interpreter cmd.exe Parse Scripts

How-to: Escape Characters, Delimiters and Quotes at the Windows command line