JScripting the Windows File System

Had your computer crash on you, or a website shows wrong, or your printer went dead on you? Come on in...

Moderator: Crew

Post Reply
User avatar
mistergreen77
Tycoon
Posts: 269
Joined: Fri Mar 31, 2006 2:09
Location: Brisbane

JScripting the Windows File System

Post by mistergreen77 »

The file system can be understood as a folder object that contains folder objects, ie. a recursive data structure. Lets use JScript to write a recursive function to handle this structure. In this example we scan all subfolders of 'Program Files' and list the .ini files it contains. This sort of script can easily be modified to copy or move files or rename files as well. I have reused it countless times just by modifying the starting parameters and the handleFiles function.

Code: Select all

// first, lets create an instance of the file system object

var fso = WScript.CreateObject("Scripting.FileSystemObject");

// now lets create an reference to starting directory

var topFolder = fso.GetFolder("c:\\Program Files\\");

// and a output file

var output = fso.CreateTextFile("c:\\output.txt",true);

// okay, now lets define a function that will access every subfolder of topDirectory recursively

function recurseFolders(tFolder,pFunction) {
  var sub = null;
  var subFolders = null;
  subFolders = new Enumerator(tFolder.SubFolders);
  pFunction(tFolder)
  for (;!subFolders.atEnd();subFolders.moveNext()) { 
   sub = subFolders.item();
   // now for the recursive magic
    recurseFolders (sub, pFunction) } 
  return true; }

// and a function to do some work with each folder

function handleFiles(tFolder) {
 var subfiles = new Enumerator(tFolder.files);
 for (;!subfiles.atEnd();subfiles.moveNext()) { 
  // in this example we are going to write the path of every .ini file to output.txt
  theFile = subfiles.item();
  extension = fso.GetExtensionName(theFile.path);
  if (extension=="ini") output.WriteLine(theFile.path); } }
  
// now to put it all together

recurseFolders(topFolder,handleFiles);

WScript.echo("Finished.");
Well this is the basics, you can make more useful scripts using arguments but this is just to show the basic principle of recursion on the file system. I have tested it using windows xp. JScripts are saved with the .js extension and you can use notepad or your favourite text editor to write them.
[size=84][color=green]“Everything should be made as simple as possible, but not one bit simpler.”[/color] - Einstein

[color=green]“There is always some madness in love. But there is also always some reason in madness.”[/color] - Nietzsche[/size]

:twisted: [url=http://forum.connect-webdesign.dk/viewtopic.php?p=5411#5411]Society of Sinister Minds.[/url]
Post Reply