views:

3446

answers:

2

Hello Here is what I want, inside the BACKUPDIR, I want to execute cscript /nologo c:\deletefile.vbs %BACKUPDIR% until number of files inside the folder is greater than 21(countfiles holds it). Here is my code:

@echo off
SET BACKUPDIR=C:\test
for /f %%x in ('dir %BACKUPDIR% /b ^| find /v /c "::"') do set countfiles=%%x

for %countfiles% GTR 21 (
cscript /nologo c:\deletefile.vbs %BACKUPDIR%
set /a countfiles-=%countfiles%
)
+2  A: 

A while loop can be simulated in cmd.exe with:

:while1
if %countfiles% leq 21 (
    :: change countfile here
    goto :while1
)

For example, the following script:

@echo off
setlocal enableextensions enabledelayedexpansion
set /a "x = 0"
:while1
    if %x% leq 5 (
        echo %x%
        set /a "x = x + 1"
        goto :while1
    )
endlocal

outputs:

0
1
2
3
4
5

For your particular case, I would start with the following. Your initial description was a little confusing. I'm assuming you want to delete files in that directory until there's 20 or less:

@echo off
set backupdir=c:\test

:loop1
for /f %%x in ('dir %backupdir% /b ^| find /v /c "::"') do set countfiles=%%x
if %countfiles% gtr 20 (
    cscript /nologo c:\deletefile.vbs %backupdir%
    goto :loop1
)
paxdiablo
exaclty what you are saying, however theres an issue that it goes into an infinite loop, seems like counfiles should be decreased inside the loop, such as set /a "countfiles = countfiles-1" but it doesn't seem to work for me.
Hellnar
@Hellnar, countfiles is set to the real value again by virtue of the fact the for-statement that calculates it is *inside* the loop. I did it that way since it wasn't clear how many files your VBScript file was deleting.
paxdiablo
If you have an infinite loop, replace "@echo off" with "::@echo off" and re-run the script. That will output the commands as they're executed and you will see what countfiles is being set to.
paxdiablo
+1  A: 
set /a countfiles-=%countfiles%

This will set countfiles to 0. I think you want to decrease it by 1, so use this instead:

set /a countfiles=countfiles-1

I'm not sure if the for loop will work, better try something like this:

:loop
cscript /nologo c:\deletefile.vbs %BACKUPDIR%
set /a countfiles-=1
if %countfiles% GTR 21 goto loop
schnaader
You can also use `set /a countfiles-=1`
Joey
I don't think that should be LEQ in the if statement, @schnaader.
paxdiablo
You are both right. Edited the answer to correct this.
schnaader