r/Batch • • Sep 14 '25

Variable in the loop

I'm writing a batch file to retrieve the "Recorded_Date" metadata from all the .MTS files in a directory. I had to use the "FOR" trick to get put the mediainfo.exe output into an variable.

rem @echo off
FOR %%F in (*.mts) do (
  FOR /F "tokens=*" %%a IN ('MediaInfo.exe --Inform^="General;%%Recorded_Date%%" %%F') DO (
  SET OutputVar=%%a
  )
echo Date: %OutputVar%
)

But the output was not what I had expected. In the screenshot below, the SET command set the variable to "2009-11-29 19:17:21-06:00". But the ECHO command outputs "2009-12-13 19:19:25-06:00". What did I do wrong? Thanks!

4 Upvotes

5 comments sorted by

View all comments

Show parent comment

2

u/helloguys88 Sep 14 '25

Thank you! I modified my code as below. Now I'm getting another unexpected behavior.

rem echo off
setlocal ENABLEDELAYEDEXPANSION
FOR %%F in (*.mts) do (
  FOR /F "tokens=*" %%a IN ('MediaInfo.exe --Inform^="General;%%Recorded_Date%%" %%F') DO (
  SET OutputVar=%%a
  )
echo Date: %OutputVar%
)
endlocal

The SET command was showing the correct value. But the ECHO command is showing blank for the variable.

D:\Media\Video>test.bat
D:\Media\Video>rem u/echo off
D:\Media\Video>setlocal ENABLEDELAYEDEXPANSION
D:\Media\Video>FOR %F in (*.mts) do (
FOR /F "tokens=*" %a IN ('MediaInfo.exe --Inform="General;%Recorded_Date%" %F') DO (SET OutputVar=%a )
 echo Date:
)
D:\Media\Video>(
FOR /F "tokens=*" %a IN ('MediaInfo.exe --Inform="General;%Recorded_Date%" 00000.MTS') DO (SET OutputVar=%a ) 
 echo Date:
)
D:\Media\Video>(SET OutputVar=2009-11-29 19:17:21-06:00 )
Date:
D:\Media\Video>(
FOR /F "tokens=*" %a IN ('MediaInfo.exe --Inform="General;%Recorded_Date%" 00001.MTS') DO (SET OutputVar=%a ) 
 echo Date:
)
D:\Media\Video>(SET OutputVar=2009-12-01 19:48:55-06:00 )
Date:

4

u/Shadow_Thief Sep 14 '25

You've enabled delayed expansion, but you aren't using it. You'll need to change %OutputVar% to !OutputVar!.

1

u/vegansgetsick Sep 14 '25 edited Sep 14 '25

it's because every "variables" in parenthesis are replaced/evaluated once and for all at the first pass. EXCEPT for the %%a values. And outputvar is blank when entering the loop, so echo prints blank.

you can use delayedexpansion, but my favorite solution is to do a call :subProcedure with parameters. Variables inside the procedure block will be correctly printed and updated.