1

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. 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. How can I get all the variables to copy correctly?

I am using Windows 7.

Batch FIle (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

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? I found a similar question here but it doesn't quite answer my case.

1 Answer 1

2

That is because of your SETLOCAL command that you use to enable delayed expansion. 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.

You can pass the value across the ENDLOCAL barrier by adding the following to the end of your script:

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.