简体   繁体   English

Windows oneliner在环境变量中设置命令输出

[英]windows oneliner to set a command output in an environment variable

As stated here Is it possible to set an environment variable to the output of a command in cmd.exe I always used that 如此处所述, 是否可以在cmd.exe中将环境变量设置为命令的输出?

mycommand.exe>%TEMP%\out.txt
set /P FOO=<%TEMP%\out.txt

But that's ugly because it creates a file. 但这很丑陋,因为它创建了一个文件。

The for method is better but complicated for方法更好但很复杂

I wanted something simple a la unix, like: 我想要一些简单的东西,例如:

mycommand.exe|set /P FOO=

No error, but FOO is not set after I run that. 没有错误,但是运行FOO之后没有设置FOO

Why is this not working? 为什么这不起作用?

Best way I can think of doing this would be to create your own little batch file that silently uses the FOR construct. 我能想到的最好方法是创建自己的小批处理文件,该文件默默使用FOR构造。 For instance, you could create a batch named BatchSet.bat, stored somewhere on your path. 例如,您可以创建一个名为BatchSet.bat的批处理,并将其存储在路径中的某个位置。 The batch would contain the following code: 该批处理将包含以下代码:

@Echo off
for /f "delims=" %%i in ('%2') do set %1=%%i
Set %1

If you run this with the following command: 如果使用以下命令运行此命令:

BatchSet MyVar whoami

You'll get something like: 您会得到类似的信息:

MyVar=servername\John

Obviously, the command you run should limit its output to a single line to be stored properly in the environment variable. 显然,您运行的命令应将其输出限制为一行以正确存储在环境变量中。 For instance, if you run it like this: 例如,如果您这样运行它:

BatchSet MyVar Vol

Then you'll only get the first line of the Vol command's output 然后,您将只获得Vol命令输出的第一行

MyVar= Volume on drive C is labeled MyDisk

But all in all, it's a fairly elegant way of doing what you were looking for. 但总而言之,这是完成所需工作的一种相当优雅的方法。

Note that the last line in the batch is simply there to provide visual output. 请注意,批处理中的最后一行只是为了提供可视输出。 It can be removed altogether. 可以将其完全删除。

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

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