【问题标题】:Batch file set wmi output as a variable批处理文件将 wmi 输出设置为变量
【发布时间】:2020-05-27 09:04:22
【问题描述】:

您好,我第一次使用 BATCH 脚本,我得到的硬盘大小如下:

wmic diskdrive get size

这很好,但我想将此值存储到一个变量中以供以后使用,例如使用 ECHO 来显示该值。

我不确定如何将上述命令的输出设置为变量。我去了:

SET hddbytes=wmic diskdrive get size

但这只是将变量设置为上述文本字符串,而不是输出。

【问题讨论】:

  • 我认为所有这些解决方案只会在列表中提供一个驱动器 - 我的驱动器列出了几个。顺便说一句,这是batch 脚本而不是BASH
  • @foxidrive 是的,当然 :) 我基本上不是一个 Windows 人,只是想着 BASH,谢谢你指出来

标签: windows batch-file


【解决方案1】:

用于批处理文件。在命令行中,将 %% 替换为 %

for /f "tokens=*" %%f in ('wmic diskdrive get size /value ^| find "="') do set "%%f"
echo %size%

或者,如果你想使用你喜欢的变量

for /f "tokens=2 delims==" %%f in ('wmic diskdrive get size /value ^| find "="') do set "myVar=%%f"
echo %myVar%

【讨论】:

  • +1.更喜欢Textvaluelist格式,因此set可以直接使用。
  • 你可以直接使用"delims="和set %%f,但这只是我在使用wmic时更喜欢设置值的方式
  • @npocmaka:是的。我明白。如果您查看答案中的第一个代码,将delims= 更改为tokens=*,您将获得相同的解决方案set "%%f"
  • 对于这两个,在 Windows 7 上的批处理文件中,我得到:'wmic diskdrive get size /value | find "="' is not recognized as an internal or external command, operable program or batch file.
  • @ashleedawg,在 W10 中测试(距答案五年,我手头没有 W7)并且正在工作。您是否检查过wmic 在您的安装中可用? path 有问题?
【解决方案2】:

你想要:

for /f %%a in ('wmic diskdrive get size^|findstr [0-9]') do echo %%a

【讨论】:

  • 实际上的问题是关于将其放入变量中
【解决方案3】:

更新:

  1. WMIC 的输出在某些环境中可能会出现尾随 回车:

    Size        <CR>
    <CR><LF>
    256052966400<CR>
    <CR><LF>
    500105249280<CR>
    <CR><LF>
    15496427520 <CR>
    <CR><LF>
    
  2. 使用 csv 格式,并使用 FOR 循环从 wmic 输出中截断想要的值:

    For /F "tokens=2,3 delims=," %%a in ('"wmic diskdrive get size,Status 
    /format:csv |findstr "[0-9]" "') do (
    echo "%%a"
    )
    

另一个批处理脚本示例:

setlocal ENABLEDELAYEDEXPANSION
:: You can change active code page as well::
@chcp 936 >NUL

:: [example] Remove all network printers:
for /F "tokens=2,3 delims=," %%a in ('"wmic printer where 'local=FALSE' get Name,PrinterStatus /format:csv |findstr "." "') do (
    echo "%%a"
    rundll32 printui.dll,PrintUIEntry /n "%%a" /dn /q
)

【讨论】:

    【解决方案4】:
    for /f "delims="  %%w in ('wmic diskdrive get size /format:Textvaluelist.xsl') do for /f "usebackq delims=" %%a in ('%%w') do set %%a
    echo %size%
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-09-15
      • 1970-01-01
      • 2019-06-23
      • 2019-08-09
      • 1970-01-01
      相关资源
      最近更新 更多