0

I am struggling really hard with parsing the output of the SC.EXE command. I want to list all services (active or inactive) that have "text" in their name.

The following code is looking for eventlog:

FOR /F "usebackq" %%G IN (`"sc query state= all" ^| find "eventlog"`) DO echo [%%G]

It would all work if it was not for the state= all parameter that you need to pass to the SC command so that you will get even inactive services.

For some not so clear reason the values for parameters in the SC command need to be separated by space and that's causing a lot of confusion.

Any help is greatly appreciated!

4

3 回答 3

2
for /f "tokens=2 delims=:" %%s in ('sc query state^= all ^| findstr /i /B /R "SERVICE_NAME:.*event" ') do echo %%s

使用冒号作为分隔符并在行首过滤 SERVICE_NAME 文本的行,然后是包含事件的任何文本,检索第二个标记(冒号后的服务名称)。

于 2013-11-12T16:25:49.953 回答
1
FOR /F %%G IN ('sc query state^= all ^| find /i "eventlog"') DO echo [%%G]

似乎 find eventlog,回显 `[SERVICE_NAME:]

于 2013-11-12T14:19:29.323 回答
0

假设 SERVICE_NAME 值中没有空格,则保留第二部分并使用冒号空格作为分隔符。

sc query state= all | find "SERVICE_NAME" | find "SQL"

SERVICE_NAME: MSSQLFDLauncher
SERVICE_NAME: MSSQLSERVER
SERVICE_NAME: MSSQLServerOLAPService
SERVICE_NAME: SQLBrowser
SERVICE_NAME: SQLSERVERAGENT
SERVICE_NAME: SQLTELEMETRY
SERVICE_NAME: SQLWriter

使用标记 2,这将采用上面的第二部分和 DO 并回显该值。在dos文件中使用%%A。但这里将使用 %A。如果您有更多令牌 2,3,则可以使用 %B。在 for 正文中转义任何将由 dos 的初始条目解释的内容。

FOR /F "tokens=2 delims=: " %A IN ('sc query state^= all ^| find "SERVICE_NAME"') DO @echo [%A] | find "SQL"


[MSSQLFDLauncher]
[MSSQLSERVER]
[MSSQLServerOLAPService]
[SQLBrowser]
[SQLSERVERAGENT]
[SQLTELEMETRY]
[SQLWriter]
于 2020-04-16T17:21:10.863 回答