简体   繁体   English

使用 Windows 批处理文件中的命令结果设置变量的值

[英]Set the value of a variable with the result of a command in a Windows batch file

When working in a Bash environment, to set the value of a variable as the result of a command, I usually do:Bash环境中工作时,要将变量的值设置为命令的结果,我通常会这样做:

var=$(command -args)

where var is the variable set by the command command -args .其中var是命令command -args设置的变量。 I can then access that variable as $var .然后我可以以$var访问该变量。

A more conventional way to do this which is compatible with almost every Unix shell is:一种与几乎所有 Unix shell 兼容的更传统的方法是:

set var=`command -args`

That said, how can I set the value of a variable with the result of a command in a Windows batch file ?也就是说,如何使用Windows 批处理文件中的命令结果设置变量的值? I've tried:我试过了:

set var=command -args

But I find that var is set to command -args rather than the output of the command.但我发现var设置为command -args而不是command -args的输出。

To do what Jesse describes , from a Windows batch file you will need to write:要执行Jesse 描述的操作,您需要从 Windows 批处理文件中编写:

for /f "delims=" %%a in ('ver') do @set foobar=%%a 

But, I instead suggest using Cygwin on your Windows system if you are used to Unix-type scripting.但是,如果您习惯了 Unix 类型的脚本,我建议您在 Windows 系统上使用Cygwin

One needs to be somewhat careful, since the Windows batch command:需要小心一点,因为 Windows 批处理命令:

for /f "delims=" %%a in ('command') do @set theValue=%%a

does not have the same semantics as the Unix shell statement:没有与 Unix shell 语句相同的语义:

theValue=`command`

Consider the case where the command fails, causing an error.考虑命令失败导致错误的情况。

In the Unix shell version, the assignment to "theValue" still occurs, any previous value being replaced with an empty value.在 Unix shell 版本中,仍然会发生对“theValue”的赋值,任何先前的值都被替换为空值。

In the Windows batch version, it's the "for" command which handles the error, and the "do" clause is never reached -- so any previous value of "theValue" will be retained.在 Windows 批处理版本中,处理错误的是“for”命令,并且永远不会到达“do”子句——因此将保留“theValue”的任何先前值。

To get more Unix-like semantics in Windows batch script, you must ensure that assignment takes place:要在 Windows 批处理脚本中获得更多类 Unix 的语义,您必须确保分配发生:

set theValue=
for /f "delims=" %%a in ('command') do @set theValue=%%a

Failing to clear the variable's value when converting a Unix script to Windows batch can be a cause of subtle errors.在将 Unix 脚本转换为 Windows 批处理时未能清除变量的值可能会导致细微错误。

Here's how I do it when I need a database query's results in my batch file:当我的批处理文件中需要数据库查询的结果时,我是这样做的:

sqlplus -S schema/schema@db @query.sql> __query.tmp
set /p result=<__query.tmp
del __query.tmp

The key is in line 2: "set /p" sets the value of "result" to the value of the first line (only) in "__query.tmp" via the "<" redirection operator.关键在第 2 行:“set /p”通过“<”重定向运算符将“result”的值设置为“__query.tmp”中第一行(仅)的值。

The only way I've seen it done is if you do this:我看到它完成的唯一方法是如果你这样做:

for /f "delims=" %a in ('ver') do @set foobar=%a

ver is the version command for Windows and on my system it produces: ver是 Windows 的版本命令,在我的系统上它生成:

Microsoft Windows [Version 6.0.6001]

Source 来源

Here are two approaches:这里有两种方法:

@echo off

:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
;;set "[[=>"#" 2>&1&set/p "&set "]]==<# & del /q # >nul 2>&1" &::
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

:: --examples

::assigning chcp command output to %code-page% variable
chcp %[[%code-page%]]%
echo 1: %code-page%

::assigning whoami command output to %its-me% variable
whoami %[[%its-me%]]%
echo 2: %its-me%


::::::::::::::::::::::::::::::::::::::::::::::::::
;;set "{{=for /f "tokens=* delims=" %%# in ('" &::
;;set "--=') do @set ""                        &::
;;set "}}==%%#""                               &::
::::::::::::::::::::::::::::::::::::::::::::::::::

:: --examples

::assigning ver output to %win-ver% variable
%{{% ver %--%win-ver%}}%
echo 3: %win-ver%


::assigning hostname output to %my-host% variable
%{{% hostname %--%my-host%}}%
echo 4: %my-host%

the output of the script:脚本的输出:

1: Active code page: 65001
2: mypc\user
3: Microsoft Windows [Version 10.0.19042.1110]
4: mypc

Explanation:解释:

1] the parts ending with &:: are end-of-line comment and can be ignored. 1]&::结尾的部分是行尾注释,可以忽略。 I've put them only for macro enclosing我把它们只用于宏封闭

2] ;; 2] ;; at the start of the line will be ignored as ;在行的开头将被忽略为; is a standard delimiter for batch script.是批处理脚本的标准分隔符。 It is put there as it reminds a comment and to further enhance where the macro definitions are assigned.它放在那里是因为它提醒注释并进一步增强宏定义的分配位置。

3] the technique used is called 'macro' it assigns command to a variable and when the variable is invoked the command is executed. 3] 使用的技术称为“宏”,它将命令分配给变量,当调用变量时,执行命令。

4] the first macro defined contains two parts: 4]定义的第一个宏包含两部分:

set "[[=>"#" 2>&1&set/p "

and

set "]]==<# & del /q # >nul 2>&1"

separated by & which allows me to define them on one line.&分隔,这允许我在一行上定义它们。 The first takes the output of a command and redirects it ot a file # .第一个获取命令的输出并将其重定向到文件# And adds set/p in order to start the reading the file with set /p technique .The second macro finishes the set /p reading with <# and then deletes the file.并添加set/p以开始使用set /p技术读取文件。第二个宏以<#完成set /p读取,然后删除文件。 The text between two macros is the name of the variable.两个宏之间的文本是变量的名称。 Something like set /p myVariable=<#类似于set /p myVariable=<#

5] The second macro contains three parts and expanded is just a for /f loop. 5]第二个宏包含三个部分,扩展只是一个for /f循环。 Probably can be done in a more elegant way.可能可以以更优雅的方式完成。

Set "dateTime="
For /F %%A In ('powershell get-date -format "{yyyyMMdd_HHmm}"') Do Set "dateTime=%%A"
echo %dateTime%
pause

在此处输入图片说明 Official Microsoft docs for for command for命令的官方 Microsoft 文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM