我需要将程序的输出分配给使用MS批处理文件的变量。
所以在GNU Bash shell中,我将使用VAR=$(应用程序arg0 arg1)。我需要在Windows中使用批处理文件的类似行为。
比如set VAR=application arg0 arg1。
类似的问题
如何在批处理文件中将命令输出设置为变量 我如何得到一个命令的结果在一个变量在窗口? 在Windows批处理文件中使用命令的结果设置变量的值 将命令的输出设置为变量(使用管道) 将命令输出分配给批处理文件中的变量
我需要将程序的输出分配给使用MS批处理文件的变量。
所以在GNU Bash shell中,我将使用VAR=$(应用程序arg0 arg1)。我需要在Windows中使用批处理文件的类似行为。
比如set VAR=application arg0 arg1。
类似的问题
如何在批处理文件中将命令输出设置为变量 我如何得到一个命令的结果在一个变量在窗口? 在Windows批处理文件中使用命令的结果设置变量的值 将命令的输出设置为变量(使用管道) 将命令输出分配给批处理文件中的变量
当前回答
@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
其他回答
除了答案之外,你不能在for循环的set部分直接使用输出重定向操作符(例如,如果你想对用户隐藏stderror输出并提供更好的错误消息)。相反,你必须用一个插入字符(^)来转义它们:
for /f %%O in ('some-erroring-command 2^> nul') do (echo %%O)
参考:重定向批处理脚本for循环中的命令输出
@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
一种方法是:
application arg0 arg1 > temp.txt
set /p VAR=<temp.txt
另一个原因是:
for /f %%i in ('application arg0 arg1') do set VAR=%%i
请注意,%%i中的第一个%用于转义后面的%,并且在批处理文件中而不是在命令行中使用上述代码时需要它。想象一下,你的test.bat有这样的东西:
for /f %%i in ('c:\cygwin64\bin\date.exe +"%%Y%%m%%d%%H%%M%%S"') do set datetime=%%i
echo %datetime%
在命令行中执行以下命令时:
for /f %%i in ('application arg0 arg1') do set VAR=%%i
我得到了错误:
%%i was unexpected at this time.
为了解决这个问题,我改为使用一个%符号,就像这样:
for /f %i in ('application arg0 arg1') do set VAR=%i
简介:
在批处理文件中使用%% 在批处理文件之外使用%(在命令行上)
@OP,你可以使用for循环来捕获程序的返回状态,如果它输出的不是数字的话