简体   繁体   English

将文件路径连接到批处理脚本中的环境变量

[英]Concatenate file paths to an environment variable in batch script

I have made a bat script that should copy the list of folders to a variable but I don't get anything in the variable. 我已经制作了一个bat脚本,该脚本应该将文件夹列表复制到变量中,但是变量中什么也没有。 In other words, when I echo the variable after my for loop I get the expected output, but in the shell outside after executing the script, I don't see anything set in my variable. 换句话说,当我在for循环之后回显变量时,我得到了预期的输出,但是在执行脚本之后在外壳程序外部,我看不到变量中有任何设置。 How can I get all the variables to copy correctly? 如何获取所有变量以正确复制?

I am using Windows 7. 我正在使用Windows 7。

Batch FIle (script.bat): 批处理文件(script.bat):

@echo off
setlocal enabledelayedexpansion enableextensions

for /r /D %%x in (*) do (
    SET PATH_VALUE=%%x;!PATH_VALUE!
)    
echo %PATH_VALUE%

Output of windows cmd utility Windows cmd实用程序的输出

C:\test> script.bat
C:\test\1;C:\test\2

C:\test> echo %PATH_VALUE%
%PATH_VALUE%

How do I get the %PATH_VALUE% as an environment variable? 如何获取%PATH_VALUE%作为环境变量? I found a similar question here but it doesn't quite answer my case. 我在这里找到了类似的问题但并不能完全解决我的问题。

That is because of your SETLOCAL command that you use to enable delayed expansion. 这是因为使用了SETLOCAL命令来启用延迟扩展。 Yes it provides the delayed expansion you need, but it also localizes environment changes. 是的,它可以提供您所需的延迟扩展,但是还可以本地化环境更改。 As soon as your batch script ends, there is an implicit ENDLOCAL , and the old environment is restored. 批处理脚本结束后,将隐式包含ENDLOCAL ,并且将还原旧环境。

You can pass the value across the ENDLOCAL barrier by adding the following to the end of your script: 您可以通过在脚本末尾添加以下内容来跨ENDLOCAL障碍传递值:

endlocal&set "PATH_VALUE=%PATH_VALUE%"

or you could write it like: 或者你可以这样写:

(
  endlocal
  set "PATH_VALUE=%PATH_VALUE%"
)

Both of the above work because the blocks of code are expanded and parsed prior to the ENDLOCAL executing, but the SET statement with the expanded value is executed after the ENDLOCAL. 上面的两个工作都是因为在执行ENDLOCAL之前对代码块进行了扩展和解析,但是具有扩展值的SET语句在ENDLOCAL之后执行。

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

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