0

In windows 2008: I'm trying to zip and copy files to a backup server. I use command line/batch file, I log the result in a log file, I now want to log also the time for each file looped.

The backupZipCopy.bat batch file:

setlocal enabledelayedexpansion
echo starting at %date% %time%>>c:\backup\resuZip.log
d:
cd \myDirectoryToBackup
FOR %%i IN (*.nsf)  DO (
echo %date% %time%>>c:\backup\resuZip.log 
"C:\Program Files\7-Zip\7z.exe"  -bd u "\\backupServer\myBackup\%%~ni.zip" "%%~fi">>c:\backup\resuZip.log
)

My problem: The time is the same for all the batch duration (the time when batch started when I expected the real time in each loop). I already specify setlocal enabledelayedexpansion which doesn't help (so do I need this or not?).

NB timethis won't solve my problem since I need time in each loop. NB2 I'm calling this batch from the window scheduler.

1 Answer 1

3

The problem is that in the line (the ( ) block is parsed as a single line), all %foo% variables are evaluated only once, before running the for loop.

The enabledelayedexpansion option does help. However, it doesn't change the parsing rules for the usual %foo% variable syntax. Instead, it introduces a new one – using ! as delimiters.

for %%i in (*.nsf) do (
    echo !date! !time!>> C:\backup\resuZip.log
)

Be very careful with this, however, as the delayed expansion happens after %foo% variables have been expanded. Therefore it will result in unexpected output if a % variable has exclamation marks in it. The cmd.exe parsing rules are outright painful at times.

I strongly recommend you use a different language for your script. PowerShell would be a good choice, considering it's part of most recent Windows releases and it has tools for managing various Windows Server components.

5
  • 1
    yep, strongly encouraged: something other than cmd.exe ... the horror .. the horror.
    – akira
    Jul 29, 2014 at 5:56
  • I get your point @akira, but could you advice a better&simple way? Jul 29, 2014 at 6:02
  • @EmmanuelGleizer: python, ruby, powershell? pick any .. not cmd.exe .. except when you have to for $reasons.
    – akira
    Jul 29, 2014 at 6:04
  • @EmmanuelGleizer: PowerShell would be very useful to learn; it is part of Windows these days, and it also has cmdlets for managing many Windows Server components. (I rarely deal with Windows myself, so I'd go with Python.) Jul 29, 2014 at 6:08
  • Thanks a lot grawity ! You solve my problem. I note I should re write this! I guess l will re-write this in power shell... stackoverflow.com/questions/18847145/… is my starting point. One more time thanks! Jul 29, 2014 at 6:10

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .