我尝试将批处理变量设置为另一个命令的输出。在 Linux/Unix 中,您可以简单地使用反引号,例如(在 csh 中)
set MY_VAR = `tail /etc/passwd`
windows 批处理中有类似的东西吗?
实际上我已经发现了一些东西,但它还没有完全发挥作用:
d:\>for /F "skip=1" %n in ('wmic OS Get CurrentTimeZone') do set TimeZone=%n
d:\>set TimeZone=120
:\>set TimeZone=
d:\>
问题是wmic
命令返回几行,否则它会正常工作。我知道要跳过第一个,但是我没能跳过第二个空行。我尝试过IF
但没有成功。
是的 - wmic 的输出有点难以处理。
使用一个技巧:在输出中搜索一个数字(findstr "[0-9]
只会返回包含数字的行):
for /F %n in ('wmic OS Get CurrentTimeZone ^|findstr "[0-9]"') do set TimeZone=%n
echo Timezone is %TimeZone%.
(用于批处理文件中使用%%n
代替%n
)
另一种方法是:
for /F %n in ('wmic OS Get CurrentTimeZone') do if not defined TimeZone set TimeZone=%n
EDIT:
我更喜欢第一个版本,因为findstr
(or find
) 转换 wmic-line-endings,所以第二个for
提到的MC ND https://stackoverflow.com/a/25340872/2152082没有必要。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)