I'm trying to get a simple value from a for /f
loop in a batch file.
Using the command wmic path win32_localtime get dayofweek
gives me the output:
C:\sendemail>wmic path win32_localtime get dayofweek
DayOfWeek
1
C:\sendemail>
So, using the following batch script, I should be able to return a result of "1":
set cmd=wmic path win32_localtime get dayofweek
for /f "tokens=1 skip=1" %%Z in ('%cmd%') do set _myday=%%Z
echo Var is %_myday%
But I don't, it sets the variable at least twice, as seen here :
C:\sendemail>set cmd=wmic path win32_localtime get dayofweek
C:\sendemail>for /F "tokens=1 skip=1" %Z in ('wmic path win32_localtime get dayofweek') do set _myday=%Z
C:\sendemail>set _myday=1
:\sendemail>set _myday=
C:\sendemail>echo Var is
Var is
C:\sendemail>
At first, I wondered why, then I realised the loop is processing the two blank lines... which it shouldn't be. according to this: http://ss64.com/nt/for_cmd.html
Skip SKIP will skip processing a number of lines from the beginning of the file. SKIP includes empty lines, but after the SKIP is complete, FOR /F ignores (does not iterate) empty lines.
Either, it's not working normally, or those lines are not blank, and are filled with something...
At any rate, how do I get just the day of the week result out of this, and ignore the rest?
About the lines contents, yes, the output from wmic
includes at the end of each line an additional carriage return character that is detected by the for
command. That is the reason for your non empty lines.
You can try with
for /f "tokens=2 delims==" %%Z in ('
wmic path win32_localtime get dayofweek /value
') do for /f %%Y in ("%%Z") do set "_myday=%%Y"
The code is asking wmic
to return the information in key=value
format and using the equal sign to tokenize the input records. As we request only the second token, for
will only process lines that return at least two tokens, lines having a key (first token), an equal sign (delimiter) and a value (second token)
But, the additional carriage return at the end of the line is also included in the value of the variable.
When the variable is used with normal syntax (%_myday%
) it is not seen, but with delayed expansion (!_myday!
) the additional carriage return will be echoed.
To remove this additional character from the variable, a second for
command has been used in the posted code.
This slight midification will work:
@ECHO OFF
set cmd=wmic path win32_localtime get dayofweek
for /f "tokens=1 skip=1" %%Z in ('%cmd%') do (
set _myday=%%Z
GOTO BREAK
)
:BREAK
echo Var is %_myday%
PAUSE
Simply jump out of the loop after reading the desired line.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With