| Document Path: | Home Page / Command Tools / SyncScan / Sample - Clean Directory |   |
This program deletes files from a directory and optionaly its sub-directories. At start, the program check command line arguments. If a required argument is missing or invalid, it prompts the user to enter one.
Required command line arguments:
//Argument 1 - the directory to clean
var dir=app.argv(0);
var fo=app.FindFile(dir);
while(fo.Valid? !fo.AttributeDirectory : true)
{
dir=app.Input("Enter a directory to clean: ");
if(!dir) // If use just hit enter, we quit
{
app.Exit(-1);
}
fo=app.FindFile(dir);
}
//Argument 2 - Sub-directories?
var yesno=app.argv(1).toLowerCase();
if(yesno!='y' && yesno!='n')
{
app.Print("Scan sub-directories? (y/n)\n");
while(yesno!='y' && yesno!='n')
{
yesno=app.getch(false).toLowerCase();
}
}
subdir=(yesno=='y'? true:false);
//Argument 3 - File extension names
var extensions=app.argv(2).toLowerCase();
while(!extensions)
{
extensions=app.Input("Enter file extension names (separated with '?'. example: ?obj?pch?opt?): ");
}
extensions=extensions.toLowerCase();
//Argument 3 - Delete or keep?
yesno=app.argv(3).toLowerCase();
if(yesno!='d' && yesno!='k')
{
app.Print("Should we delete or keep files with the specified extension names? (d/k)\n");
while(yesno!='d' && yesno!='k')
{
yesno=app.getch(false).toLowerCase();
}
}
var delExtensions=(yesno=='d'? true : false);
//We have all the required arguments now
//Prompt the user to press any key to continue. This gives the user a chance to terminate the program by Ctrl+C
app.Print("\nClean " + dir + (subdir? " and sub-directories" : " only") + (delExtensions? "delete" : "keep") + " files with one of the extension names: " + extensions+"\n");
app.Print("Press any key to continue....\n");
app.getch();
app.ScanDirectory(dir, subdir, CleanCallback);
function CleanCallback(dirFlag, fo)
{
switch(dirFlag)
{
case 2: //fo is the root directory passed to app.ScanDirectory
app.Print("\nStart cleaning " + fo.FullPath+"\n");
break;
case -2: //End of the job
app.Print("\nEnd of cleaning " + fo.FullPath+"\n");
break;
case 0: //fo is a file
var ext="?"+fo.ExtensionName.toLowerCase()+"?";
var i=extensions.indexOf(ext);
if(delExtensions? (i>=0) : (i<0))
{
app.Print("Delete " + fo.FullPath+"\n");
fo.Delete();
}
break;
case 1: //Enter a sub-directory
app.Print("Begin scanning sub-directory: "+fo.FullPath+"\n");
break;
case -1: //Leave a sub-directory
app.Print("End of scanning sub-directory: "+fo.FullPath+"\n");
break;
}
//Give the user a chance to stop this programm by pressing ESC
if(app.kbhit())
{
var ch=app.getch();
if(ch==27)
{
app.Print("*** Abort ***\n");
return(-1);
}
}
}