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

Batch file acting on each item in a FOR loop

我正在尝试遍历系统中的所有 dimm 并将它们写入文本文件。我知道我可以使用 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的信息?

编辑以显示我启用的延迟扩展线

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

我是这样解决的:

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! 之间的确切区别是什么,但我知道感叹号会在读取变量时强制扩展变量。