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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20219527/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 11:07:54  来源:igfitidea点击:

Batch file set wmi output as a variable

windowsbatch-file

提问by twigg

Hello having my first go with a BATCH script, I'm getting the size of the HDD as follow:

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

wmic diskdrive get size

Which works fine but I'd like to store this value into a variable for later use, such as using ECHO to display the value.

这工作正常,但我想将此值存储到一个变量中以备后用,例如使用 ECHO 显示该值。

I'm not sure how I set the output of the above command to a variable. I went with:

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

SET hddbytes=wmic diskdrive get size

But this just sets the variable to the above text string and not the output.

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

回答by MC ND

For usage in batch file. From command line, replace %% with %

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

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

Or, if you want to use you prefered variable

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

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

回答by Matt Williamson

You want:

你要:

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

回答by Y.Ganothr

Updated:

更新:

  1. WMIC's output could get a trailing Carriage Returnin 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"
    )
    
  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"
    )
    

Another Batch Script Example:

另一个批处理脚本示例:

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
)

回答by npocmaka

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%