I try to set a batch variable to an output of another command. In Linux/Unix you can simply use backticks, e.g. (in csh)
set MY_VAR = `tail /etc/passwd`
Is there something similar available in windows batch?
Actually I found already something but it is not fully working:
d:\>for /F "skip=1" %n in ('wmic OS Get CurrentTimeZone') do set TimeZone=%n
d:\>set TimeZone=120
:\>set TimeZone=
d:\>
The problem is the wmic
commands returns several lines, otherwise it would work fine. The first I know to skip, however I did not manage to skip the second empty line. I tried with IF
but no success.
I suggest following batch code:
The FOR loop is exited with command GOTO after the value of interest is assigned to environment variable
TimeZone
.The entire FOR loop can be optimized to a single command line:
Exiting the FOR loop after having the value of interest avoids the problem with wrong parsing of Unicode (UTF-16 Little Endian) encoded output of WMIC by FOR which otherwise would result in deleting the environment variable
TimeZone
. For details on wrong parsing of Unicode output by FOR see answer on How to correct variable overwriting misbehavior when parsing output?yes - the output of wmic is a bit ugly to handle.
Use a trick: search for a number in the ouput (
findstr "[0-9]
will only return lines, that contain a number):(for use in a batchfile use
%%n
instead of%n
)Another way is:
EDIT:
I prefer the first version, as
findstr
(orfind
) converts the wmic-line-endings, so the secondfor
mentioned by MC ND is not neccessary.(to use in a batch file, remember to double the percent signs)
The added
/value
inwmic
changes its output tokey=value
format. Thedelims
clause infor
command indicates a=
as a separator. Thetokens
clause ask to retrieve only the second token/field in the line. As the only line with two tokens is the line with the required data, only this line is processed.BUT, wmic output includes an aditional carriage return at the end of its output, that needs to be removed from the variable. An aditional
for
command can be used. The resulting command will beOr, for a batch file