我想在命令行实用程序中构建一个用作参数的字符串。字符串将根据我在变量中定义的某些服务的存在构建。到目前为止,我有以下代码:
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET "PRODS=Service1 Service2 Service3"
REM Let's see what's installed.
SET NEWPRODS=
FOR %%i in (%PRODS%) DO (
%comspec% /c %WINDIR%\system32\sc.exe query %%i | %WINDIR%\system32\findstr /C:"RUNNING">nul
IF NOT ERRORLEVEL 1 (
SET NEWPRODS=%%i
ECHO !NEWPRODS!
)
)
如何输出(让我们假设服务1和3已经找到并且正在运行)是这样的:Service1,Service3?
提前致谢。
答案 0 :(得分:0)
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET "PRODS=Service1 Service2 Service3"
REM Let's see what's installed.
SET "NEWPRODS="
FOR %%i in (%PRODS%) DO sc.exe query %%i | findstr /C:"RUNNING">nul && SET "NEWPRODS=!NEWPRODS!%%i,"
REM Trim trailing comma if string is not empty
IF NOT "%NEWPRODS%"=="" SET "NEWPRODS=%NEWPRODS:~0,-1%"
ECHO(%NEWPRODS%
pause
不要做
echo %SomeVariable%
如果变量为空,则显示当前的ECHO状态。 设置字符串时请使用引号,这样就不会出现任何意外的空格。