@echo off ::r.bat: delete random files from directory :: ::usage: r dir [count ["auto"]] :: ::Will prompt for count if not provided. ::Negative value for count means "delete all but". For example, :: r c:\stuff -10 :: ::will randomly delete all but 10 messages from c:\stuff :: ::if "auto" flag is given, will not prompt before deleting. (This could ::be dangerous.) :: ::This sets ERRORLEVEL to 1, I think, because setlocal doesn't set ERRORLEVEL at ::all on DOS/Win9x/ME verify badarg 2>nul setlocal ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION if errorlevel 1 goto bad if "%1"=="" ( echo You must specify a directory goto :EOF ) ::count the files in the directory set i=0 set filelist= ::it would seem that set /a uses 32-bit signed integer arithmetic for %%a in (%1\*) do ( set /a i+=1 set file!i!=%%a ) set MAXFILES=%i% if %MAXFILES% GTR 327679 ( echo Error: directory has more than 327679 files. goto :EOF ) if "%2"=="" ( echo There are %MAXFILES% files in directory "%1%". How many do you want to delete? set /p DELFILES=^> ) ELSE set DELFILES=%2 if %DELFILES% LSS 0 ( set /a DELFILES+=MAXFILES set /a LEAVING=MAXFILES-DELFILES echo Will delete !DELFILES! files, leaving !LEAVING!. ) if %DELFILES% EQU 0 ( echo Nothing to do goto :EOF ) if /I "%3" NEQ "auto" ( ::note space at end of next line set /p resp=Are you sure? [yn]^ if /I "!resp!" NEQ "y" goto :EOF ) if %DELFILES% EQU %MAXFILES% ( echo You know, you could just use del * del /Q %1\* echo ALL files deleted. goto :EOF ) if %DELFILES% GTR %MAXFILES% ( echo You can't delete more than there is. goto :EOF ) ::now we need to make an array of unique random numbers between 0 and DELFILES-1 ::how the hell do we do this in a batch file where you can't have (a) random ::numbers greater than 32767 and (b) arrays? ::the answer is (a) stick an extra random digit on %RANDOM% to get a random ::number between 0 and 327679, and (b) use variables like n1, n2, n3, n4 instead ::of arrays ::Another problem: there's no equivalent to PHP or JavaScript eval. But if you ::use set /a you don't have to use %variable% syntax; you can just do ::set /a foo=bar to assign the value of %bar% to foo, provided bar is an ::integer. so set bar0=2 & set i=0 & set /a foo=bar%i% puts 2 in the variable ::foo. set i=0 :loop1 set n%i%=%i% set /a i+=1 if %i% NEQ %MAXFILES% goto loop1 set i=0 set /a RANDMAX=MAXFILES - 1 set FORARGS= :loop2 set rand=%RANDOM%%RANDOM:~-1% set /a r=%RAND% %% (%RANDMAX%) set FORARGS=%FORARGS% %i% ::r is the random number that I want to use set /a r%i%=n%r% set /a n%r%=n%RANDMAX% set /a t=n%RANDMAX% set /a RANDMAX-=1 set /a i+=1 if %i% NEQ %DELFILES% goto loop2 set i=0 set j=0 echo Now starting delete set i=0 for %%a in (%1\*) do ( for %%b in (%FORARGS%) do ( set /a t=r%%b if !t!==!i! ( echo DELETING FILE "%%a" del "%%a" ) ) set /a i+=1 ) goto :EOF :bad echo Could not enable command extensions and delayed expansion. echo Are you using Windows 2000/XP? NT4 might work too.