Asignar la salida de un programa a una variable


Necesito asignar la salida de un programa a una variable usando un archivo MS batch.

Así que en GNU Bash shell usaría VAR=$(application arg0 arg1). Necesito un comportamiento similar en Windows usando un archivo por lotes.

Algo así como set VAR=application arg0 arg1.

Author: lospejos, 2010-02-24

8 answers

Una forma es:

application arg0 arg1 > temp.txt
set /p VAR=<temp.txt

Otro es:

for /f %%i in ('application arg0 arg1') do set VAR=%%i

Tenga en cuenta que el primer % en %%i se usa para escapar del % después de él y es necesario cuando se usa el código anterior en un archivo por lotes en lugar de en la línea de comandos. Imagina, tu test.bat tiene algo como:

for /f %%i in ('c:\cygwin64\bin\date.exe +"%%Y%%m%%d%%H%%M%%S"') do set datetime=%%i
echo %datetime%
 328
Author: Carlos Gutiérrez,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-08 13:12:17

Como una adición a esta respuesta anterior , se pueden usar tuberías dentro de una instrucción for, escapadas por un símbolo de comillas:

    for /f "tokens=*" %%i in ('tasklist ^| grep "explorer"') do set VAR=%%i
 55
Author: Renat,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 11:54:59

@OP, puede usar para bucles para capturar el estado de retorno de su programa, si produce algo que no sea números

 8
Author: ghostdog74,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-02-24 02:47:30

Asumiendo que la salida de su aplicación es un código de retorno numérico, puede hacer lo siguiente

application arg0 arg1
set VAR=%errorlevel%
 7
Author: akf,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-02-24 02:37:34

Al ejecutar: for /f %%i in ('application arg0 arg1') do set VAR=%%i estaba recibiendo error: %%era inesperado en este momento. Como solución, tuve que ejecutar lo anterior como for /f %i in ('application arg0 arg1') do set VAR=%i

 3
Author: Munish Mehta,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-07 11:14:52

Además de la respuesta, no puede usar directamente los operadores de redirección de salida en la parte set del bucle for (por ejemplo, si desea ocultar la salida stderror de un usuario y proporcionar un mensaje de error más agradable). En su lugar, usted tiene que escapar de ellos con un caret carácter (^):

for /f %%O in ('some-erroring-command 2^> nul') do (echo %%O)

Referencia: Redirigir la salida del comando en el bucle for del script por lotes

 1
Author: Kubo2,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:18:24
@echo off
SETLOCAL ENABLEDELAYEDEXPANSION

REM Prefer backtick usage for command output reading:
REM ENABLEDELAYEDEXPANSION is required for actualized
REM  outer variables within for's scope;
REM within for's scope, access to modified 
REM outer variable is done via !...! syntax.

SET CHP=C:\Windows\System32\chcp.com

FOR /F "usebackq tokens=1,2,3" %%i IN (`%CHP%`) DO (
    IF "%%i" == "Aktive" IF "%%j" == "Codepage:" (
        SET SELCP=%%k
        SET SELCP=!SELCP:~0,-1!
    )
)
echo actual codepage [%SELCP%]

ENDLOCAL
 0
Author: rcm,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-01 13:39:41

Escribí el guión que hace ping google.com cada 5 segundos y los resultados de registro con el tiempo actual. Aquí puede encontrar la salida a las variables "commandLineStr" (con índices)

@echo off

:LOOPSTART

echo %DATE:~0% %TIME:~0,8% >> Pingtest.log

SETLOCAL ENABLEDELAYEDEXPANSION
SET scriptCount=1
FOR /F "tokens=* USEBACKQ" %%F IN (`ping google.com -n 1`) DO (
  SET commandLineStr!scriptCount!=%%F
  SET /a scriptCount=!scriptCount!+1
)
@ECHO %commandLineStr1% >> PingTest.log
@ECHO %commandLineStr2% >> PingTest.log
ENDLOCAL

timeout 5 > nul

GOTO LOOPSTART
 0
Author: Ja Vy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-02 12:25:09