问题
Here's the command I'm trying to run. I wanted to get the service name for my SQL Server 2008 instance
FOR /F "delims==" %%G IN ('wmic service where (displayname like ^"%%sqlserver2008%%^")') DO echo %%G
回答1:
First you need to get the correct WMIC command, then you need to get it to work within a FOR command.
The basic WMIC command you are looking for is:
wmic service where "displayName like '%%sqlserver2008%%'" get name
Now there are a few complications with FOR /F. WMIC output is in unicode and it has a weird interaction with FOR /F - somehow every line that FOR /F parses includes an extra carriage return at the end. The unwanted carriage return is included in each FOR /F iteration. Yuck :(
One effective solution is to request CSV format, with at least one extra unwanted column beyond the column you are interested in. Then you can set DELIMS and TOKENS to get the desired column(s). In your case, the State column appears after the Name, so it is a good candidate.
WMIC /CSV format includes an extra Node column at the front.
WMIC /CSV format includes a blank line and a header line at the top that can be skipped by using SKIP=2.
Here is a fully functioning FOR /F solution.
for /f "skip=2 tokens=2 delims=," %%A in (
'wmic service where "displayName like '%%sqlserver2008%%'" get name^,state /format:csv'
) do echo %%A
来源:https://stackoverflow.com/questions/14249147/i-cant-get-the-right-syntax-to-use-wmic-in-batch-file