I can't get the right syntax to use WMIC in batch file

╄→尐↘猪︶ㄣ 提交于 2019-12-13 06:39:02

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!