Search code examples
variablesbatch-filewmic

How can I set a WMIC Variable in a batch file?


I created this simple batch file and it sets the variable twice. Once with the answer I'm looking for, and then a second time blank which erases the variable.

for /f "tokens=1 delims==" %%f in ('WMIC PRODUCT WHERE "Name like "%%iTunes%%"" get name') do set "myVar=%%f"
echo %myVar%

It gives me the below result.

C:\Batch>disktest

C:\Batch>for /F "tokens=1 delims==" %f in ('WMIC PRODUCT WHERE "Name like "%iTun
es%"" get name') do set "myVar=%f"

" \Batch>set "myVar=Name

" \Batch>set "myVar=iTunes

" \Batch>set "myVar=

C:\Batch>echo
ECHO is on.

C:\Batch>

So somewhere I'm not escaping correctly with a ^ or I don't know what I'm missing. Can anyone help me out?

This is Windows 7x64 but I'd also like to use it in XP SP3 as well.


Solution

  • After some experiments with the newly discovered wmic :) I think your problem is that, by default, it will list the results you want along with the title of the column first and following empty line at the end.

    To filter the results from wmic, add | FIND "xxx", e.g.,

    wmic product where "name like 'xxx'" get name | find "xxx"
    

    This will filter out the line containing the title (which is why you're getting "Name" in your results) and the final blank line.

    In fact, on further reflection, you may be able to remove the "where" clause completely, replacing it with the "find", so:

    wmic product get name | find "xxx"