Files and Folders

The special object FileSystemObject is designed to provide access to files and folders. This object is implemented in the script runtime library, and because of this is an extension of JScript or VBScript scripting engines, but not a part of the WSH. That is, if we need to use another script engine (like PerlScript) we cannot use this object (unless we use cross-script functions in a .wsf files).

Since FileSystemObject is a part of the scripting type library we need to access this object via the Scripting object. In JScript we can create FileSystemObject by using the creator of the ActiveXObject, which is designed to return references to ActiveX objects. The following code shows how to create an instance of the FileSystemObject

var fs = new ActiveXObject("Scripting.FileSystemObject");
To destroy an instance of the FileSystemObject and free up the memory it uses we need to assign to the variable a new value (for example, an empty string):
fs = ""; // destroy the FileSystemObject variable
The object of the FileSystemObject type has only one property Drives that provides a collection (list) of all physical and logical drives on the system and a lot of methods. Some of the methods are given in the table below:
Methods of FileSystemObject
Method Description
BuildPath Appends the path information to an existing file path.
CopyFile Copies file from one location to another.
CopyFolder Copies folders and their contents from one location to another.
CreateFolder Creates a folder.
CreateTextFile Creates a text file and returns a TextStream object.
DeleteFolder Deletes a folder and all of its contents.
DeleteFile Deletes a file.
DriveExists Determines if a drive exists.
FileExists Determines if a file exists.
FolderExists Determines if a folder exists.
GetAbsolutePathName   Returns the full path to a file or a folder.
GetBaseName Returns the base name of a file or a folder.
GetDrive Returns a Drive object.
GetDriveName Returns a drive name.
GetExtensionName Returns a file extension from a path.
GetFile Returns a File object.
GetFileName Returns a filename from a path.
GetFolder Returns a Folder object.
GetParentFolderName Returns a parent folder name from a path.
GetTempName Returns a randomly generated file or folder name that can be used with CreateTextFile.
MoveFile Moves files from one location to another.
MoveFolder Moves folders and their contents from one location to another.
OpenTextFile Opens an existing text file and returns TextStream object.

Drives

As we mentioned above the property Drives provides an access to all drives on the system. However, we need to learn a new technique to be able to deal with a collection of elements. Because items in a collection are not directly accessible, we need to use a new Enumerator object. An instance of this object will have the same elements and will provide several methods to give us an access to them. To create an instance of the Enumerator object we need to write this
var drv_list = new Enumerator( fs.Drives );
Now, new object drv_list contains all the drives and it also has several methods to provide an access to them. The methods we are interested in are: Thus, to loop through all elements of the we need to write a code like
while( ! drv_list.atEnd() ){
   drive = drv_list.item();
   // get some information about the drive
   drv_list.moveNext();
}
The method item() returns an element of the list. The type of the element depends on the type of the list. In our case, we will have an instance of the Drive object. The Drive object allows you to gain information about the various drives attached to a system, either physically or over a network. Its properties allow you to obtain information about: The property DriveType returns an integer number indicating the type of the drive. Some of the types are in the table below:
Type   Description
0 Unknown type drive
1 Removable drive or a floppy drive
2 Hard drive
3 Network drive
4 CD-ROM drive
5 Virtual RAM drive

The following example show how to print some information about all drives:

var fs = new ActiveXObject("Scripting.FileSystemObject");
var drvs = new Enumerator(fs.Drives);
var dType = new Array("unknown", "Removable", "Fixed", "Network", "CD-ROM", "RAM disk");
var msg;

while( ! drvs.atEnd() ){
   drive = drvs.item();
   msg = "";
   msg += "Drive " + drive.DriveLetter + ":\n";
   msg += "\tType: " + dType[drive.DriveType] + "\n";
   if( drive.IsReady ){
      msg += "\tDrive is ready\n";
      msg += "\tFile system: " + drive.FileSystem + "\n";
      msg += "\tTotal space: " + Math.roundd(drive.TotalSize/(1024*1024)) + " MB\n";
      msg += "\tFree space: " + Math.round(drive.FreeSpace/(1024*1024)) + " MB\n";
   }
   else
      msg += "\tDrive is not ready\n";
   WScript.Echo(msg);
   drvs.moveNext();
}

Folders

The FileSystemObject allows us to do the following things with folders:
  • view folder contents
  • check folder properties
  • create a new folder
  • delete, copy, and move folders

    To get the contents of a folder we need to use method GetFolder() of the FileSystemObject that returns an instance of the object Folder. This object contains the following properties:
    Property Description
    Attributes Sets or returns the attributes of files or folders. The attribute argument can have any of the following values or any logical combination of the following values.
    DateCreated Returns the date and time that the specified file or folder was created. Read-only.
    DateLastAccessed Returns the date and time that the specified file or folder was last accessed. Read-only.
    DateLastModified Returns the date and time that the specified file or folder was last modified. Read-only.
    Drive Returns the drive letter of the drive on which the specified file or folder resides. Read-only.
    Files Returns a Files collection consisting of all File objects contained in the specified folder, including those with hidden and system file attributes set.
    IsRootFolder Returns true if the specified folder is the root folder; false if it is not.
    Name Sets or returns the name of a specified file or folder. Read/write.
    ParentFolder Returns the folder object for the parent of the specified file or folder. Read-only.
    Path Returns the path for a folder.
    ShortName Returns the short name used by programs that require the earlier 8.3 naming convention.
    ShortPath Returns the short path used by programs that require the earlier 8.3 file naming convention.
    Size Returns the size, in bytes, of all files and subfolders contained in the folder.
    SubFolders Returns a Folders collection consisting of all folders contained in a specified folder, including those with hidden and system file attributes set.
    Type Returns information about the type of a file or folder. For example, for files ending in .TXT, "Text Document" is returned.
    As we can see to get information about contents of a folder we need to use properties Files and Subfolders of the object Folder. Both of these properties return a collection of objects; that is, we need the new technique we have learned earlier to get the items if these collections. The example below illustrates how to get all names of files from a folder "C:\temp\"

    var fs = new ActiveXObject("Scripting.FileSystemObject");
    var fldr = fs.GetFolder("c:\\temp");
    var file_list = new Enumerator(fldr.Files);
    var msg = "";
    while( ! file_list.atEnd() ){
       fname = file_list.item();
       msg += fname + ":\n";
       file_list.moveNext();
    }
    WScript.Echo(msg);
    
    In a similar way we can get all subfolders of a given folder. Please note that method GetFolder() takes a string argument that specifies which folder we would like to work with.

    To examine all properties of a folder we just need to look at the values of the properties of the object Folder.

    HW: write a script that takes one argument name of a folder and prints all possible information about this folder including all subfolders and all files.

    The methods of the FileSystemObject that allows us to work with folders are

    Files

    To work with files, WSH provides special File object. The table below shows all properties of the object.
    Property Description
    Attributes Sets or returns file properties. This property contains the same values as the Attributes property of the Folder object.
    DateCreated Returns the date and time the file was created.
    DateLastAccessed Returns the date the file was last accessed.
    DateLastModified Returns the date and time the file was last modified.
    Drive Returns the drive letter on which the file resides.
    Name Returns the filename.
    ParentFolder Returns the Folder object of the parent folder.
    Path Returns the path to the file.
    ShortName Returns the MS-DOS (8.3) compliant name of the file.
    ShortPath Returns the MS-DOS compliant path to the file.
    Size Returns the byte size of the file.
    Type Returns the type of the file.
    Before we can examine file properties, we have to get a file object by calling GetFile() method of the FileSystemObject object. This method takes a string containing a file name as an argument and returns an object of the type File that contains all information about the file. For example, to print size and the date of last modification of the file autoexec.bat we need to do this
    var fs = new ActiveXObject("Scripting.FileSystemObject");
    var fl = fs.GetFile("c:\\autoexec.bat");
    WScript.Echo("c:\\autoexec.bat "+fl.Size+" "+fl.DateLastModified);
    

    The only read-write property of the File object i property Attributes. This property can be used both for retrieving file attributes and setting new file attributes. This property contains an integer code. This code is a combination of values from the table below.
    Attribute values for Files and Folders.
    Constant Value Description
    Normal 0 A normal file with no attributes set.
    ReadOnly 1 A read-only file. Attribute is read-write.
    Hidden 2 A hidden file. Attribute is read-write.
    System 4 A system file. Attribute is read-write.
    Volume 8 A disk drive volume label. Attribute is read-only.
    Directory 16 A folder or directory. Attribute is read-only.
    Archive 32 A file with the archive bit set (meaning it has changed since last backup). Attribute is read-write.
    Alias 64 A link or a shortcut. Attribute is read-only.
    Compressed 128 A compressed file. Attribute is read-only.
    To change an attribute of a file, we need to assign a new value to the Attributes property. For example, to make the config.sys file hidden we need to set attribute to the value Hidden:

    var fs = new ActiveXObject("Scripting.FileSystemObject");
    var fl = fs.GetFile("c:\\config.sys");
    fl.Attributes = Hidden;
    

    The FileSystemObject has several methods to work with files. Some of these methods are discussed in this section.

    In-class assignment

    Please write a script that synchronizes contents of two folders. The script should take two folder names as arguments and make sure that they contain the same information. If a file is absent in one folder, but present in anothe, the file should be copied over to the folder where it's missing. If both folders contain the same file but different verions of the file the new version should be copied. Same thing should be recursively done for all subfolders.


    References