问题
Here is the code:
@echo off
setlocal EnableDelayedExpansion
for /f "tokens=* skip=1 delims=\" %%b in ('wmic /node:%CompName% COMPUTERSYSTEM GET USERNAME') do echo %%b
Output:
domain\username
ECHO is off.
Expected result:
username
Notes: The variable CompName
will be set prior. This can be ignored.
This code is a part of a larger code I am writing for this batch file where I'll just need to pull the username
to have it set as a variable.
Pseudo code:
set TargetUsername = (results from above)
future code (possibly used for other parts of the code)
回答1:
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.
回答2:
I figured it out guys: I just set tokens=2:
Output:
username
回答3:
This should work (I haven't tested it):
@echo off
for /f "tokens=1 skip=1 delims=\" %%b in ('wmic /node:%CompName% COMPUTERSYSTEM GET USERNAME') do (set TargetUsername=%%b)
set TargetUsername=(%TargetUsername%
echo%TargetUsername%
pause
来源:https://stackoverflow.com/questions/45152339/why-is-echo-is-off-displayed-after-output-of-data-of-interest-on-running-wmic