如何将环境变量的值设置为 Windows 批处理文件中命令的输出?

如何将环境变量的值设置为 Windows 批处理文件中命令的输出?

如何将环境变量设置为 Windows 批处理文件中命令的输出?该命令将返回一个约 32 个字符的单个值(例如,键入 myfile.txt)。

答案1

尝试运行以下命令:

for /f "delims=" %a in ('mybatchfile.bat') do @set myenvvar=%a
echo %myenvvar%

答案2

暂时地:

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


永久性:

for /f "delims=" %a in ('command to run') do @setx example_environment_variable=%a

旁注,set仅为该命令进程/窗口设置它,但setx为整个用户/系统设置它。

答案3

或者:

for /f "usebackq delims==" %v in (`echo new_value`) do set new_var=%v 

为什么有人想使用这个版本?

根据for /?帮助,人们可能需要在处理文件名中的双引号时使用它(事实上,这就是我最终在这里的结果):


usebackq        - specifies that the new semantics are in force,
                  where a back quoted string is executed as a
                  command and a single quoted string is a
                  literal string command and allows the use of
                  double quotes to quote file names in
                  file-set.

[...]

Finally, you can use the FOR /F command to parse the output of a
command.  You do this by making the file-set between the
parenthesis a back quoted string.  It will be treated as a command
line, which is passed to a child CMD.EXE and the output is captured
into memory and parsed as if it was a file.  So the following
example:

  FOR /F "usebackq delims==" %i IN (`set`) DO @echo %i

would enumerate the environment variable names in the current
environment.

相关内容