Search code examples
batch-filescriptingwmi-querywmic

Batch Store WMIC Query with multiple conditions into variable


I am using this line in a batch script which successfully stores a user's SID value into a variable called SID

FOR /F "tokens=1,2 delims==" %%s IN ('wmic path win32_useraccount where name^='%_curruser%' get sid /value ^| find /i "SID"') DO SET SID=%%t

I'd like to modify this to include an "AND" in the WMIC Query but I can't seem to get it to work.

The correct query is:

wmic path win32_useraccount where "name='%USERNAME%' and Domain like 'HB%'" GET SID /VALUE

Can someone please help me translate this so the SID value is stored into a variable?


Solution

  • You need to escape the % percent character in Domain like 'HB%' by doubling it as follows:

    FOR /F "tokens=1,2 delims==" %%s IN ('
        wmic path win32_useraccount where "name='%USERNAME%' and Domain like 'HB%%'" GET SID /VALUE ^| find /i "SID"
    ') DO for /F "tokens=*" %%i in ("%%t") do SET "SID=%%i"
    

    Here the for loops are

    • %%s to retrieve the SID value;
    • %%i to remove the ending carriage return in the value returned (wmic behaviour): each output line ends with 0x0D0D0A (CR+CR+LF) instead of common 0x0D0A (CR+LF).

    See Dave Benham's WMIC and FOR /F: A fix for the trailing <CR> problem