简体   繁体   中英

Output of WMIC command in variable

for %%f in ('wmic service where 'name like 'Steam Client%%'") do set Service=%%f
echo %Service%

What am I doing wrong?

for /F "tokens=*" %%f in ('wmic service where "name like "Steam%%"" get Name ^| findstr /V /R "^$"') do set Service=%%f
echo %SERVICE%

Output

Steam Client Service

Mistakes in your code:

  • Did not use /F switch with for-loop
  • Used single and double-quotes intermixed.
  • Did not specify a specific property to get with the get clause
  • Did not filter extra output with findstr

Isn't the last bracket in ('wmic service where 'name like 'Steam Client%%'") supposed to be ' not " ? In any case, I have never tried to use wmic service, only wmic win32_localtime which looked like this: FOR /F %%F IN ('wmic path win32_localtime get dayofweek^|Findstr [0-6]') DO SET DOW=%%F

EDIT: I notice several places where you have gone wrong here, at least in the parts that I can understand. If you want the output of the code to be evaluated by a FOR statement you require /F infront of FOR and before the variable. You also normally need to start and end the brackets containing the command with a single quote ('). Like so: for /f %%f in ('wmic service where name like "Steam Client%%"') do set Service=%%f echo %Service%

For any assistance with WMIC queries this might help

Hope this helps.

This is how I'd do it.

The second for loop strips some problematic characters from the output, much in the same way as the FindStr example, only quicker. I then implement a Call to strip the trailing spaces which pad the end of the returned Get string.

@Echo Off
For /F "Skip=1 Delims=" %%A In (
    '"WMIC Service Where (Name Like 'Steam%%') Get Name"'
) Do For /F "Delims=" %%B In ("%%A") Do Call :Sub %%B
Echo("%Service%"
Timeout -1
GoTo :EOF

:Sub
Set "Service=%*"
GoTo :EOF

The above code is completely untested as I'm using an android device.

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