Search code examples
for-loopbatch-filecmdsetwmic

How to Create Batch code to set each line of output into separate variables


I use this code to set first output line into variable but can't set second or other line into another variables.

wmic memorychip get capacity

Output:

Capacity
4294967296
4294967296
8589934592
4294967296

My code:

for /f "tokens=2 delims==" %%A in ('wmic memorychip get capacity /value ^| find /i "Name="') do set capacity=%%A

echo %capacity%

Output:

4294967296

But I need some code like:

do set capacity1=%%A & capacity2=%%B & capacity3=%%C & capacity4=%%D

echo %capacity1%
echo %capacity2%
echo %capacity3%
echo %capacity4%

I need to set each line into separate variables.


I need separate variables like %capacity1% and %capacity2% etc. I'll use each value to calculate using more code.


Solution

  • In order to generate a collection of variables (usually called an array, but batch technically doesn't have arrays (it's complicated)), you'll have to set up a variable to keep track of a counter and increment that every time a new line is read.

    In order to update and use a variable inside of the same for loop, you'll need to enable delayed expansion (see this for more information about that).

    Also, because wmic outputs in UTF-16 and each line ends in \r\r\n instead of \r\n, you'll need to run each line through a second for loop.

    @echo off
    setlocal enabledelayedexpansion
    
    set "capacity_counter=0"
    for /f "tokens=2 delims==" %%A in ('wmic memorychip get capacity /value ^| find /I "Capacity="') do (
        for /f %%B in ("%%~A") do (
            set /a capacity_counter+=1
            set "capacity[!capacity_counter!]=%%B"
        )
    )
    
    for /L %%A in (1,1,!capacity_counter!) do echo Capacity %%A: !capacity[%%A]!