Search code examples
batch-filewmic

Setting the output of WMIC commands to variable .bat


I am trying to add a currently logged in user feature to a .bat support menu i have created.

I am trying to get just the username of the currently logged in user.

I have tried to the following;

The command;

%MID% is a variable set elsewhere in the file.

wmic /node:%MID% computersystem get username

This returns;

Username DOMAIN\USER

I am trying to capture the username only.

Tried to do it using tokens and delims but can't seem to get the syntax correct, tried;

for /f "tokens=1 delims= " %%a ('wmic /node:%MID% computersystem get username') do set CUSER=%%a

CUSER returns blank.

Any assitance will be very much appreciated.

I understand there are other ways to do this, but i feel accomplishing this task will assist my learning and understanding of WMIC and .bat syntax, I would like to solve this very specifically.

Appreciate ya face in advance.


Solution

  • Using your method, this is probably how I would retrieve the UserName only:

    For /F "Skip=1 Tokens=2 Delims=\" %%G In ('""%__AppDir__%wbem\WMIC.exe" /Node:"%MID%" ComputerSystem Get UserName"') Do Set "CUSER=%%G"