Search code examples
batch-filecmdwmic

Strange results quering WMI information


I write simple batch file to fast check network interface status:

@echo off
cls
setlocal
for /f "tokens=2 delims==" %%q in ('wmic path win32_networkadapter where "netconnectionid like '%%ovpn_wintun%%'" get netconnectionstatus /format:list ^| find ^/i ^"NetConnectionStatus^"') do (
echo q variable is: %%q
IF %%q LEQ 2 echo 1. q less or equal %%q
IF %%q EQU 2 echo 2. q equal %%q
IF %%q GEQ 2 echo 3. q greater or equal %%q
IF %%q LEQ 3 echo 4. q less or equal %%q
IF %%q EQU 3 echo 5. q equal %%q
IF %%q GEQ 3 echo 6. q greater or equal %%q
)
endlocal
pause

And receive unexpected results:

Execution results

Compare variables as string have no result.

Can someone explain me, please, what is it and it is fixable in batch script?


Solution

  • The issue is caused by the fact that wmic output is not only Unicode, but also has an output with line terminals like CRCRLF.

    You could observe this by outputting %%q to a file and examining the file with editplus or a similar real text editor.

    Here's a quick-fix (noting that I've modified the wmic command to suit my system)

    @ECHO OFF
    SETLOCAL
    for /f "tokens=2 delims==" %%q in ('wmic path win32_networkadapter where "netconnectionid like '%%ethernet%%'" get netconnectionstatus /format:list ^| find ^/i ^"NetConnectionStatus^"') do (
     echo q variable is: %%q
     SET /a QQ=%%q
     SETLOCAL enabledelayedexpansion
     IF !qq! LEQ 2 echo 1. q less or equal %%q
     IF !qq! EQU 2 echo 2. q equal %%q
     IF !qq! GEQ 2 echo 3. q greater or equal %%q
     IF !qq! LEQ 3 echo 4. q less or equal %%q
     IF !qq! EQU 3 echo 5. q equal %%q
     IF !qq! GEQ 3 echo 6. q greater or equal %%q
     endlocal
    )
    
    SET Q
    GOTO :EOF