user8139631
user8139631

Reputation:

WMIC output in batch. How to remove corruption?

Want to detect if program is running in VirtualBox.

@echo off
setlocal enabledelayedexpansion
set count=0
for /f "tokens=1 delims==" %%a in ('wmic csproduct get name') do (
  set name!count!=%%a
  set /a count=!count!+1
)
if /i not !name1!==virtualbox (
echo NOT VIRTUALBOX
echo !name1!
) else (
echo VIRTUALBOX
echo !name1!
)
endlocal

But !name1! string is corrupt. By adding text AFTER echo !name1!, variable !name1! gets eaten by added text and text appears BEFORE string. Not able to perform if compare with such string. Any suggestions?

Upvotes: 0

Views: 463

Answers (1)

aschipfl
aschipfl

Reputation: 34909

Wrap around another for /F loop:

...
for /F "delims=" %%a in ('wmic CSProduct get Name') do (
    for /F "tokens=1 delims==" %%b in ("%%a") do (
        set "name!count!=%%b"
        set /A count+=1
    )
)
...

The problem is that wmic produces Unicode output, which for /F does not convert properly to ANSI text, it leaves some artefacts (orphaned carriage-return characters) behind; a second for /F loop removes them.


The command line wmic CSProduct get Name produces an output like:

Name
VirtualBox

Therefore you could add the skip=1 option to the outer for /F loop to not process the header. In addition, the option string tokens=1 delims== of the inner for /F loop does not make sense, because there should not appear any = anyway:

...
for /F "skip=1 delims=" %%a in ('wmic CSProduct get Name') do (
    for /F "delims=" %%b in ("%%a") do (
        set "name!count!=%%b"
        set /A count+=1
    )
)
...

Alternatively, you could add the /VALUE option to the wmic command line to get an output like this:

Name=VirtualBox

In this case, the code needs to be adapted like this:

...
for /F "delims=" %%a in ('wmic CSProduct get Name /VALUE') do (
    for /F "tokens=1* delims==" %%b in ("%%a") do (
        set "name!count!=%%c"
        set /A count+=1
    )
)
...

Upvotes: 4

Related Questions