Deleting a Folder

Microsoft® Windows® 2000 Scripting Guide

From time to time, folders need to be deleted. For example, you might have a file server that includes a folder for each individual user. When a user leaves the organization, the folder belonging to that user should be deleted; this helps ensure that the orphaned folder does not use up valuable disk space. Likewise, you might have a script that stores temporary files within a folder. Before the script finishes, you might want to delete that folder and thus remove all the temporary files.

The DeleteFolder method provides a way to delete a folder and all its contents. The DeleteFolder method requires a single parameter: the path of the folder to be deleted. For example, the script in Listing 4.8 deletes the folder C:\FSO and everything in it.

Listing 4.8 Deleting a Folder


Set objFSO = CreateObject("Scripting.FileSystemObject")

The DeleteFolder method deletes all items immediately; it does not ask for confirmation of any kind or send the items to the Recycle Bin.

Using Wildcards to Delete Folders

One of the main advantages of using scripts as a management tool is that scripts can operate on multiple items at the same time. For example, rather than delete a series of folders one by one, you can use scripts to delete a set of folders in a single operation.

The FileSystemObject allows you to use wildcard characters to delete a specific set of folders. For example, suppose you have the folder structure shown in Figure 4.1 and you want to delete all the subfolders beginning with the letter S.

Figure 4.1 Sample Folder Structure


This can be done by using the following command; when run against the sample folder structure, the command deletes the folders Scripts, Subfolder1, and Subfolder2:


This command deletes all the subfolders beginning with the letters Su, meaning only Subfolder1 and Subfolder2 will be deleted:


Wildcard characters can appear only in the final part of the path parameter. For example, this command, which features a wildcard character in the middle of the path parameter, generates a "Path not found" error: