简体   繁体   中英

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.

What about skipping first and last line?

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

As you are skipping 1 line ( skip=1 ) and at second line you are looking if %cuser% is defined. If it's not, set the content to the result.
At next line, as it will be defined, it will do nothing.

I will recommend you putting the /node in quotation marks because if it contains dashes ( - ) it might fail.

I only realized now that you wanted username only:

@for /f "tokens=2delims=\" %%a in ('wmic /node:"%MID%" computersystem get username /value ^| findstr "="') do @set CUSER=%%a
echo %CUSER%

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM