【问题标题】:How to set batch variable to output of another script如何将批处理变量设置为另一个脚本的输出
【发布时间】:2014-10-10 00:48:20
【问题描述】:

我尝试将批处理变量设置为另一个命令的输出。在 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,但没有成功。

【问题讨论】:

    标签: variables batch-file output


    【解决方案1】:

    是的 - 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
    

    编辑:

    我更喜欢第一个版本,因为findstr(或find)转换了wmic-line-endings,所以MC ND提到的第二个for不是必需的。

    【讨论】:

      【解决方案2】:

      我建议以下批处理代码:

      @echo off
      for /F "skip=1" %%I in ('%SystemRoot%\System32\wbem\wmic.exe OS Get CurrentTimeZone') do (
         set "TimeZone=%%I"
         goto BelowLoop
      )
      :BelowLoop
      echo Time zone difference is: %TimeZone%
      

      在将感兴趣的值分配给环境变量TimeZone 后,使用命令GOTO 退出FOR 循环。

      整个FOR循环可以优化为单个命令行:

      @echo off
      for /F "skip=1" %%I in ('%SystemRoot%\System32\wbem\wmic.exe OS Get CurrentTimeZone') do set "TimeZone=%%I" & goto BelowLoop
      :BelowLoop
      echo Time zone difference is: %TimeZone%
      

      在获得感兴趣的值后退出 FOR 循环可避免 WMIC 的 Unicode (UTF-16 Little Endian) 编码输出进行错误解析的问题FOR 否则会导致删除环境变量TimeZone。有关 FOR 错误解析 Unicode 输出的详细信息,请参阅How to correct variable overwriting misbehavior when parsing output?

      上的答案

      【讨论】:

        【解决方案3】:
        for /f "tokens=2 delims==" %a in ('wmic OS get CurrentTimeZone /value') do set "timeZone=%a"
        

        (要在批处理文件中使用,请记住将百分号加倍)

        wmic 中添加的/value 将其输出更改为key=value 格式。 for 命令中的delims 子句指示= 作为分隔符。 tokens 子句要求仅检索该行中的第二个标记/字段。由于唯一带有两个标记的行是包含所需数据的行,因此仅处理此行。

        但是,wmic 输出在其输出末尾包含一个额外的回车,需要从变量中删除。可以使用附加的for 命令。生成的命令将是

        for /f "tokens=2 delims==" %a in ('wmic OS get CurrentTimeZone /value') do for /f %b in ("%a") do set "timeZone=%b"
        

        或者,对于批处理文件

            for /f "tokens=2 delims==" %%a in (
                'wmic OS get CurrentTimeZone /value'
            ) do for /f %%b in ("%%a") do set "timeZone=%%b"
        
            echo %timeZone%
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-12-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-09-15
          相关资源
          最近更新 更多