批处理文件将WMI输出设置为变量

10

你好,我第一次尝试使用批处理脚本,正在按以下方式获取硬盘驱动器的大小:

wmic diskdrive get size

这个命令很有效,但我想将这个值存储到一个变量中以便以后使用,比如使用ECHO显示该值。

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

SET hddbytes=wmic diskdrive get size

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


我认为所有这些解决方案只会在列表中给出一个驱动器 - 我的列表中有几个驱动器。顺便说一下,这是“批处理”脚本而不是“BASH”。 - foxidrive
@foxidrive 当然可以 :) 我绝对不是Windows用户,只是想到了BASH,感谢你指出来。 - twigg
4个回答

15

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

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 - npocmaka
你可以直接使用 "delims="set %%f,但这只是我在使用 wmic 时喜欢设置值的方式。 - npocmaka
@npocmaka:是的,我明白。如果你看一下答案中的第一段代码,将delims=改为tokens=*,你就会得到相同的解决方案set "%%f" - MC ND
对于这两种情况,在Windows 7上的批处理文件中,我得到了以下错误消息:'wmic diskdrive get size /value | find "="' 未被识别为内部或外部命令、可执行程序或批处理文件。 - ashleedawg
@ashleedawg,在W10上测试过(距离回答已经五年了,我手头没有W7),并且可以正常工作。您是否检查过wmic在您的安装中是否可用?路径有问题吗? - MC ND

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

1
实际上,这个问题是在询问如何将它放入一个变量中。 - ashleedawg

1

更新:

  1. WMIC's output could get a trailing Carriage Return in some environment:

    Size        <CR>
    <CR><LF>
    256052966400<CR>
    <CR><LF>
    500105249280<CR>
    <CR><LF>
    15496427520 <CR>
    <CR><LF>
    
  2. use csv format, and use FOR loop to truncate the wanted value from the wmic output:

    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
)

0
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%

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接