Alex
Alex

Reputation: 1030

Batch file for loop to unzip files and get timestamps of zip file contents

I have a daily process which generates some zip files out of files that are being created by other processes. I need to create a daily log file which indicates the timestamps the contents of one specific file of each zip file that is found.

I created the following batch script which seemed to work yesterday on my test system, but not anymore today, no idea why...

set VersionDirectory=C:\Test\VersionX\
set ResultOutputFile=C:\Test\LogFile.txt

for /f %%f in ('dir /b %VersionDirectory%\Installable\Packages\pattern*.zip') do (
    mkdir %temp%\%%f\
    unzip -extract -dir %VersionDirectory%\Installable\Packages\%%f %temp%\%%f\ > nul
    for %%a in (%temp%\%%f\InstallScript.xml) do set InstallScriptXMLDate=%%~ta
    rmdir /s /q %temp%\%%f\
    echo       %%f [package from %InstallScriptXMLDate%] >> %ResultOutputFile%
)

Short summary of what this file is supposed to do:

  1. Loop through each pattern*.zip file in C:\Test\VersionX\ directory
  2. unzip this file to the %temp%\%%f directory (where %%f is the filename)
  3. Get the timestamp of the %temp%\%%f\InstallScript.xml and put it in the %InstallScriptXMLDate% variable
  4. Delete the %temp%\%%f directory
  5. Echo the filename (%%f) and timestamp (%InstallScriptXMLDate%) into the log file

As of now the log file just contains the filenames, followed by the string '[package from ]' string, but missing the actual date timestamp

The unzipping and removing of the zip files is working flawlessly, it's just the timestamp that's not being set.

Upvotes: 2

Views: 3465

Answers (1)

Joey
Joey

Reputation: 354466

You are setting a variable and using it in the same block. This cannot work in cmd because environment variables are expanded when a statement is parsed not when it's executed. So when the loop is run all variables have already been replaced with the values they had before the loop.

Put

setlocal enabledelayedexpansion

at the start of your batch and use !InstallScriptXmlDate! instead of %InstallScriptXmlDate%.

Another note: for is perfectly capable of iterating over files by itself, you almost never need to iterate over dir /b output with for /f. In fact, it can introduce problems that can be avoided with

for %%f in (%VersionDirectory%\Installable\Packages\pattern*.zip)

Upvotes: 3

Related Questions