Search code examples
variablesbatch-file

Saving command into variable


I've question about this variables.How can I store result of a command into a variable? For example: saving drive serial into location variable. thanks. E.g:

@ECHO OFF
SET location=vol
ECHO We're working with %location%

Solution

  • for /f "delims=" %%x in ('your command and parameters') do set "var=%%x"
    

    where the 'single quotes' are required around the command from which you wish to save output.


    Edit - now we know which command.

    Comment - one variable can contain up to ~8,000 characters.

    Here's a routine that will set the values in $1...$whatever and the entire set in $all with each field enclosed in angle-brackets.

    @ECHO OFF
    SETLOCAL
    SET "$all="
    FOR /f "tokens=1*delims=:" %%a IN (
      'systeminfo 2^>nul^|findstr /n /r "$"'
      ) DO (
     SET "$%%a=%%b"
     FOR /f "tokens=*" %%c IN ("%%b") DO CALL SET "$all=%%$all%%<%%c>"
     SET /a max=%%a
    )
    
    SET $
    pause
    FOR /l %%z IN (1,1,%max%) DO CALL ECHO %%$%%z%%
    
    GOTO :EOF