简体   繁体   中英

SC Query returns errors when used in BATCH FILE 'FOR' loop

Trying to use the following line of code in a Batch File FOR loop:

FOR /F "delims=" %%g IN ('sc query type=service ^| FIND /I "bthserv"') DO ( ECHO %%g )

The command in brackets works successfully when used from CMD Prompt.

However, in a FOR loop it simply returns:

[SC] EnumQueryServicesStatus:OpenService FAILED 123:

The filename, directory name, or volume label syntax is incorrect.

Is anyone familiar with this error and how to get the FOR loop to report all services with the specific, or similar name(s)?

[Edit /]

Even changing the command to this fails with the same message:

FOR /F "delims=" %%g IN ('sc query type^= service ^| FIND /I "bthserv"') DO ( ECHO %%g )

To begin with, your title is confusing because it uses queryex not query as in your code.

In addition to that query type=service is not valid, it should be query type= service , (the space after the = is required) .

However, I'm a little confused also by your command, I'm unsure whether you're wanting to know if there's an active service named bthserv , or if there's an active service with a name containing the case insensitive string bthserv .

If you're wanting to know if there's an active service named bthserv , you should really just query it by name, query bthserv . From there you can simply use && and || for successful and unsuccessful commands, (I've just used Echo commands below) .

Example:

@%__AppDir__%sc.exe query bthserv 1> NUL && (Echo bthserv is an installed service) || Echo bthserv is not an installed service

Alternatively, you can use the ErrorLevel .

Example:

@%__AppDir__%sc.exe query bthserv 1> NUL
@If ErrorLevel 1 (Echo bthserv is not an installed service)Else Echo bthserv is an installed service

If you're wanting to know if there's an active service with a name containing the case insensitive string bthserv , (not matching it) , then the command is okay.

However, when you run that command within a , the = character is treated as a delimiter by the cmd.exe instance, the command is passed to. You'll therefore need to escape it, using the caret, ^ . In addition to that, if you want the matched service name to be captured, you'll need to select everything after the first token, using the default      and TAB delimiters.

Example:

@For /F "Tokens=1,*" %%G In ('%__AppDir__%sc.exe query type^= service ^| %__AppDir__%find.exe /I "bthserv"') Do @Echo %%H

However, you could also enclose the entire string passed to the cmd.exe instance in doublequotes, and not need to escape anything.

Example:

@For /F "Tokens=1,*" %%G In ('"%__AppDir__%sc.exe query type= service | %__AppDir__%find.exe /I "bthserv""') Do @Echo %%H

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM