How do I get the result of a command in a variable in windows? How do I get the result of a command in a variable in windows? windows windows

How do I get the result of a command in a variable in windows?


The humble for command has accumulated some interesting capabilities over the years:

D:\> FOR /F "delims=" %i IN ('date /t') DO set today=%iD:\> echo %today%Sat 20/09/2008

Note that "delims=" overwrites the default space and tab delimiters so that the output of the date command gets gobbled all at once.

To capture multi-line output, it can still essentially be a one-liner (using the variable lf as the delimiter in the resulting variable):

REM NB:in a batch file, need to use %%i not %isetlocal EnableDelayedExpansionSET lf=-FOR /F "delims=" %%i IN ('dir \ /b') DO if ("!out!"=="") (set out=%%i) else (set out=!out!%lf%%%i)ECHO %out%

To capture a piped expression, use ^|:

FOR /F "delims=" %%i IN ('svn info . ^| findstr "Root:"') DO set "URL=%%i"


If you have to capture all the command output you can use a batch like this:

@ECHO OFFIF NOT "%1"=="" GOTO ADDVSET VAR=FOR /F %%I IN ('DIR *.TXT /B /O:D') DO CALL %0 %%ISET VARGOTO END:ADDVSET VAR=%VAR%!%1:END

All output lines are stored in VAR separated with "!".

@John: is there any practical use for this? I think you should watch PowerShell or any other programming language capable to perform scripting tasks easily (Python, Perl, PHP, Ruby)


To get the current directory, you can use this:

CD > tmpFileSET /p myvar= < tmpFileDEL tmpFileecho test: %myvar%

It's using a temp-file though, so it's not the most pretty, but it certainly works! 'CD' puts the current directory in 'tmpFile', 'SET' loads the content of tmpFile.

Here is a solution for multiple lines with "array's":

@echo offrem ---------rem Obtain line numbers from the filerem ---------rem This is the file that is being read: You can replace this with %1 for dynamic behaviour or replace it with some command like the first example i gave with the 'CD' command.set _readfile=test.txtfor /f "usebackq tokens=2 delims=:" %%a in (`find /c /v "" %_readfile%`) do set _max=%%aset /a _max+=1set _i=0set _filename=temp.datrem ---------rem Make the listrem ---------:makeListfind /n /v "" %_readfile% >%_filename%rem ---------rem Read the listrem ---------:readListif %_i%==%_max% goto printListrem ---------rem Read the lines into the arrayrem ---------for /f "usebackq delims=] tokens=2" %%a in (`findstr /r "\[%_i%]" %_filename%`) do set _data%_i%=%%aset /a _i+=1goto readList:printListdel %_filename%set _i=1:printMoreif %_i%==%_max% goto finishedset _data%_i%set /a _i+=1goto printMore:finished

But you might want to consider moving to another more powerful shell or create an application for this stuff. It's stretching the possibilities of the batch files quite a bit.