title: Using endlocal set variables in a batch file, but the variables are never available outside of the setlocal/endlocal block
body: <p>I'm trying to set the value of a variable that is inside a SETLOCAL, inside a FOR loop and inside an IF statement. However, it never seems to work. I tried using a SET statement at the ENDLOCAL statement, but that doesn't seem to actually set anything. Echoing the variable after that only echos the original set value of 0.</p>
  
  <pre><code>@ECHO off
  
  SET pathsource=K:
  SET sourcefile=0
  SET counter=0
  
  SETLOCAL enableextensions enabledelayedexpansion
  
  REM Get the newest pptx file in the specified directory. Get the filename and last modified timestamp
  FOR /f "tokens=1-3,5*" %%a IN ('dir ^"%pathsource%\*.pptx^" /a-d-h-s /o-d /tw ^| find /i ^".pptx^"') DO (
      REM echo !counter!
  
      REM only get the first row by using a counter
      IF !counter! EQU 0 (
          REM variables are: a-date, b-time, c-am/pm, d&amp;e-filename
          ECHO %%a %%b %%c %%d %%e
  
          SET sourcefile=%%d %%e
      )
  
      SET /A counter+=1
  )
  
  
  ENDLOCAL &amp; (
      SET "sourcefile=%sourcefile%"
  )
  
  ECHO %sourcefile%
  
  REM do other stuff with the %sourcefile% variable after this
  </code></pre>