title: Windows CMD Batch: FOR /R with DelayedExpansion
body: <p>On my desktop, there is a folder named <strong>"test"</strong>. Inside this folder is two files, <strong>"file1.txt"</strong> and <strong>"file2.txt"</strong>.</p>
  
  <p>Take a look at this simple batch script:</p>
  
  <pre><code>@ECHO OFF
  
  SET test="C:\Users\Tyler\Desktop\test"
  
  ECHO %test%
  FOR /R %test% %%F IN (*) DO (
      ECHO %%F
  )
  </code></pre>
  
  <p>As you might expect, it outputs the following:</p>
  
  <pre><code>"C:\Users\Tyler\Desktop\test"
  C:\Users\Tyler\Desktop\test\file1.txt
  C:\Users\Tyler\Desktop\test\file2.txt
  </code></pre>
  
  <p>Now take a look at this variation:</p>
  
  <pre><code>@ECHO OFF
  
  SETLOCAL ENABLEDELAYEDEXPANSION
  
  SET test="C:\Users\Tyler\Desktop\test"
  
  ECHO !test!
  FOR /R !test! %%F IN (*) DO (
      ECHO %%F
  )
  
  ENDLOCAL
  </code></pre>
  
  <p>I would expect its output to be no different. However, here it is:</p>
  
  <pre><code>"C:\Users\Tyler\Desktop\test"
  </code></pre>
  
  <p>It appears that <code>!test!</code> gets expanded in the <code>ECHO !test!</code> line, but not in the <code>FOR /R !test!</code> line, becoming just <code>!test!</code>. Since that is, of course, not a valid path, the FOR /R loop never iterates.</p>
  
  <p>Why is this? What am I missing?</p>