批处理文件作用于FOR循环中的每个项目

时间:2017-04-14 19:20:39

标签: batch-file cmd wmic

我正在尝试遍历系统中的所有dimms并将它们写入文本文件。我知道我可以使用WMIC的/Append或CMD的重定向(>>),但是附加输出Unicode和批处理文件重定向输出的其他部分是ANSI。另外,两种标准方法都会输出大量空白行。

echo off
setlocal EnableDelayedExpansion
set _invpath="c:\temp\%COMPUTERNAME%-Inventory.txt"
for /f "tokens=2 delims==" %%f in ('wmic memorychip get devicelocator /value') do (
  if [!f] NEQ [] (
    set "MemoryDeviceLocator=%%f"
    set _prefix=%MemoryDeviceLocator:~0,4%
    if [%_prefix%]==[DIMM] (
       for /f "usebackq tokens=2 delims==" %%g in (`wmic memorychip where 'devicelocator^="%MemoryDeviceLocator%"' get capacity /value ^| find "="`) do set "Capacity=%%g"
       for /f "usebackq tokens=2 delims==" %%h in (`wmic memorychip where 'devicelocator^="%MemoryDeviceLocator%"' get serialnumber /value ^| find "="`) do set "SerialNumber=%%h"
       for /f "usebackq tokens=2 delims==" %%i in (`wmic memorychip where 'devicelocator^="%MemoryDeviceLocator%"' get speed /value ^| find "="`) do set "Speed=%%i"
       echo %MemoryDeviceLocator%=%MemoryDeviceLocator% >> %_invpath%
       echo %MemoryDeviceLocator%Capacity=%Capacity% >> %_invpath%
       echo %MemoryDeviceLocator%SerialNumber=%SerialNumber% >> %_invpath%
       echo %MemoryDeviceLocator%Speed=%Speed% >> %_invpath%
    )
  )
)

这会按照我想要的方式格式化输出,但只显示最后一个DIMM,而不是每个DIMM。例如:

DIMM2=DIMM2 
DIMM2Capacity=4294967296 
DIMM2SerialNumber=9169FG56 
DIMM2Speed=1333
DIMM2=DIMM2 
DIMM2Capacity=4294967296 
DIMM2SerialNumber=9169FG56
DIMM2Speed=1333

如何修改批处理以输出DIMM1的信息?

编辑以显示我的enabledelayedexpansion行

1 个答案:

答案 0 :(得分:0)

我设法解决了这个问题。我道歉我启用了延迟扩展,我应该包含批处理文件的那部分。

以下是我如何解决它:

echo off
setlocal EnableDelayedExpansion
set _invpath="c:\temp\%COMPUTERNAME%-Inventory.txt"
for /f "tokens=2 delims==" %%f in ('wmic memorychip get devicelocator /value') do (
  call set "MemoryDeviceLocator=%%f"
  call set _prefix=!MemoryDeviceLocator:~0,4!
  if [!_prefix!]==[DIMM] (
    echo !MemoryDeviceLocator!=!MemoryDeviceLocator! >> %_invpath%
    for /f "usebackq tokens=2 delims==" %%g in (`wmic memorychip where 'devicelocator^="!MemoryDeviceLocator!"' get capacity /value ^| find "="`) do call set "Capacity=%%g"
    echo !MemoryDeviceLocator!Capacity=!Capacity! >> %_invpath%
    for /f "usebackq tokens=2 delims==" %%g in (`wmic memorychip where 'devicelocator^="!MemoryDeviceLocator!"' get serialnumber /value ^| find "="`) do call set "SerialNumber=%%g"
    echo !MemoryDeviceLocator!SerialNumber=!SerialNumber! >> %_invpath%
    for /f "usebackq tokens=2 delims==" %%g in (`wmic memorychip where 'devicelocator^="!MemoryDeviceLocator!"' get speed /value ^| find "="`) do call set "Speed=%%g"
    echo !MemoryDeviceLocator!Speed=!Speed! >> %_invpath%
  )
)

我不是100%确定%variable%!variable!之间的确切区别是什么,但我确实知道感叹号在读取时会强制扩展变量。