0

When I run this in a batch file:

for /d %%i in ("%SystemDrive%\Users\*") do (
  set myvar=%%i\apple
  set myvar=%myvar%\orange
)

My output looks like this:

set myvar=C:\Users\Joe\apple
 set myvar=\orange

set myvar=C:\Users\Bob\apple
 set myvar=\orange

...

I'm expecting to see set myvar=C:\Users\Joe\apple\orange. Why does myvar appear to be have an empty value even though you can see it being set with one?

Jason
  • 103
  • 4
  • 4
    This is the classic delayed expansion problem. See http://stackoverflow.com/questions/10558316/example-of-delayed-expansion-in-batch-file. – bgoldst Apr 04 '16 at 19:27
  • @bgoldst I tried adding `setlocal ENABLEDELAYEDEXPANSION` but that didn't help. What would the batch file need to look like to output what I'm expecting? – Jason Apr 04 '16 at 19:40
  • 2
    You also must use exclamation marks on delayed expansions, rather than percents. So the second assignment must be changed to `set myvar=!myvar!\orange`. – bgoldst Apr 04 '16 at 19:50

2 Answers2

0

Per the comments, this generates the expected result:

setlocal ENABLEDELAYEDEXPANSION
for /d %%i in ("%SystemDrive%\Users\*") do (
  set myvar=%%i\apple
  set myvar=!myvar!\orange
)
Jason
  • 103
  • 4
0

Another solution is to use call. For example:

for /d %%i in ("%SystemDrive%\Users\*") do call :MyFunction
exit
:MyFunction
set myvar=%%i\apple
set myvar=%myvar%\orange
Jason
  • 103
  • 4