2

I have many archive folder which stores the backup files. each folder increases daily.

I need to delete all files except for recent N copies in each of them, N was defined by a variable from the parent loop.

%%a is a number from parent loop, then use another for loop to delete

for /F "usebackq skip=%%a" %%x in (`dir /TW /O:-D /B %%b`) do del %%x

The error reports

%a" was unexpected at this time.

How to fix this?

valpa
  • 319
  • 9
  • 15

3 Answers3

2

As it is not possible to use a variable for skip, you need to work around that limitation somehow.

Some alternatives:

  1. Hardcode the N (number of copies to keep) by putting the actual value in the for loops
  2. Instead of using inline dircommand to produce the list of entries implement another script that outputs only those entries you want to delete (then you might be able to set your N in just one place)
  3. Pipe the output of dir to a utility which filters out the N lines from the beginning of the listing (I'm not aware of such, but it's possible that some of the GNU utils - of which there exists a Windows port - could do that).
zagrimsan
  • 327
  • 3
  • 13
2

You can use a variable in the parameters portion of a for loop, just not a variable from another for loop. Here's a little contrived example that lists the contents of the %TEMP% directory 10 times, skipping one more line each time through the loop. This should be a representative example of what you're trying to do:

@echo off

for /l %%a in (1,1,10) do call :innerloop %%a > %%a.txt
goto :EOF

:innerloop
for /f "usebackq skip=%1" %%i in (`dir /s /a /b "%TEMP%"`) do echo %%i
Evan Anderson
  • 141,881
  • 20
  • 196
  • 331
1

This would be a good script to write in PowerShell.

$n = 5

$FoldersList = Dir e:\Archive

foreach($Folder in $FoldersList)
{
    Dir $Folder | 
        Sort-Object CreationTime -Descending | 
        Select-Object -Skip $n | 
        Remove-Item -whatif
}

In this case, Powershell makes for a very clean and easy to maintain script.

Test it before you run it on your archive because I didn't test it much on my end. Remove the -WhatIf when you are ready.

kevmar
  • 141
  • 2
  • I cannot use Powershell because it requires security policy change in the server which I don't have the admin rights – valpa Nov 27 '14 at 04:34
  • You can start powershell like this from cmd: `powershell.exe -ExecutionPolicy remotesigned` and the security policy is changed just for your session without changing it for the server. No admin rights needed. – kevmar Dec 01 '14 at 19:14