1

I am trying to make a batch script that will take the names of all sub-folders in a directory as variables for use elsewhere.

The section of code that is confusing me is:

 for /d %%D in (C:\Users\tcsupport\Desktop\Test\*) ^
 do (SET test=%%D
 echo %%D
 echo %test%
 echo %test:~32%)

The sub folders in the directory 'Test' are: 1, 2#, 3, ads, and ghf.
These are just random names for testing.

The output I am getting is:

C:\Users\tcsupport\Desktop\Test\1  
C:\Users\tcsupport\Desktop\Test\ghf  
ghf  
C:\Users\tcsupport\Desktop\Test\2#  
C:\Users\tcsupport\Desktop\Test\ghf  
ghf  
C:\Users\tcsupport\Desktop\Test\3  
C:\Users\tcsupport\Desktop\Test\ghf  
ghf  
C:\Users\tcsupport\Desktop\Test\ads  
C:\Users\tcsupport\Desktop\Test\ghf  
ghf  
C:\Users\tcsupport\Desktop\Test\ghf  
C:\Users\tcsupport\Desktop\Test\ghf  
ghf 

but I was expecting:

C:\Users\tcsupport\Desktop\Test\1  
C:\Users\tcsupport\Desktop\Test\1  
1  
C:\Users\tcsupport\Desktop\Test\2#  
C:\Users\tcsupport\Desktop\Test\2#  
2#  
C:\Users\tcsupport\Desktop\Test\3  
C:\Users\tcsupport\Desktop\Test\3  
3  
C:\Users\tcsupport\Desktop\Test\ads  
C:\Users\tcsupport\Desktop\Test\ads  
ads  
C:\Users\tcsupport\Desktop\Test\ghf  
C:\Users\tcsupport\Desktop\Test\ghf  
ghf  

Can anyone explain why this is happening or think of a way around it?

Vomit IT - Chunky Mess Style
  • 40,038
  • 27
  • 84
  • 117
  • 1
    This is due to delayed extensions. Unfortunately I am not able to write an answer right now. – LPChip Jul 08 '16 at 14:14
  • 2
    Possible duplicate of [Variables in batch file not being set when inside IF?](http://superuser.com/questions/78496/variables-in-batch-file-not-being-set-when-inside-if), [Using Call SET to Designate a Variable in a Dos Batch “For” Loop](http://superuser.com/questions/528446/using-call-set-to-designate-a-variable-in-a-dos-batch-for-loop), etc. – Ƭᴇcʜιᴇ007 Jul 08 '16 at 14:51

1 Answers1

1

Looking at the information in the links provided by Techie007 i found my answer.

Delayed Expansion was the issue. Changing the code to the following solved the problem.

 Setlocal EnableDelayedExpansion  
 for /d %%D in
 (C:\Users\tcsupport\Desktop\Test\*) ^  
 do (SET test=%%D  
 echo %%D  
 echo !test!  
 echo !test:~32!)

Sorry about the question duplication.

Vomit IT - Chunky Mess Style
  • 40,038
  • 27
  • 84
  • 117