There are multiple issues causing ECHO is off.
output on running the batch code.
The first one is using tokens=*
which results in getting assigned to loop variable b
always the entire line independent on delims=\
option.
The second issue is caused by the fact that wmic always outputs the data Unicode encoded using UTF-16 Little Endian format with byte order mark (BOM) with always a blank line at end of output. The command for fails to interpret the Unicode output correct as it interprets the last blank line as line having just a carriage return which is assigned to loop variable b
too. This bug of for results in execution of echo
with a carriage return which means echo without any parameter and the result is getting output the echo status. For details about wmic output and the wrong interpretation of last blank line by for see answers on How to correct variable overwriting misbehavior when parsing output?
The solution here is:
@echo off
for /F "skip=1 tokens=2 delims=\" %%I in ('%SystemRoot%\System32\wbem\wmic.exe /node:"%COMPUTERNAME%" COMPUTERSYSTEM GET USERNAME') do set "ComputerUserName=%%I"
echo Computer user name: %ComputerUserName%
echo Current user name: %USERNAME%
The environment variable COMPUTERNAME
is a predefined Windows environment variable.
The computer name can contain a space character and therefore it is recommended to enclose it in double quotes.
This batch code works because there is no second token when for interprets wrong the blank line at end of wmic Unicode output and therefore the command set is executed only once on processing all 3 lines of wmic output.