通过 cmd.exe /C 调用时工作 cmd 命令无法正确执行

通过 cmd.exe /C 调用时工作 cmd 命令无法正确执行

for我正在尝试通过调用它来执行包含循环的一行命令cmd /C

该命令本身执行for循环来检查服务是否正在运行(在本例中为 JBoss),如果停止则以错误代码退出:

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

如果我在cmd窗口中输入它或在文件中使用它.bat(如果我替换%%%,则它可以正常工作。

但是,如果我尝试使用cmd /C(像这样)来调用它

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

我收到错误| was unexpected at this time

有人能告诉我如何在cmd不使用批处理文件的情况下调用它吗?

答案1

您可以cmd /c " commands "在命令中使用:

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

或者,在for循环命令中"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

  • 您还可以使用另一个选项通过运算符执行相同的操作&&
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

观察:该命令将在同一行中找到:findstr STATE.*STOPPED

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


Windows 命令解释器 cmd.exe 如何解析脚本

操作方法:在 Windows 命令行中转义字符、分隔符和引号

相关内容