Cybermonk
Cybermonk

Reputation: 524

get list of folders from local drive using vbscript

I want to delete all the documents(.doc) files from my computer, for that I know how to get the list of sub folders from a folder, but not how to get the list of folders from the root directory(Ex C:)

subfoldersInFolder = folder.subFolder

Gives all the subfolders of a folder. but supposedly that I want all the folders from C:,

 Set colDrives = objFSO.Drives
 For Each objDrive in colDrives
 objDrive.subFolder  //doesn't work
 Next

Upvotes: 8

Views: 31008

Answers (2)

user3575900
user3575900

Reputation: 31

The drive object doesn't have a SubFolder property. What it does have is a RootFolder property using which you can navigate to the root folder and then on using the SubFolder property of the folder object, get all the containing folders just like Mr @Bond mentioned. However, if you would like to loop through all the folders of all the drives, this will do it

On Error Resume Next
Set FSO = CreateObject("Scripting.FileSystemObject")
Set colDrives = FSO.Drives
For Each objDrive in colDrives
    For Each objFolder In FSO.GetFolder(objDrive.RootFolder).SubFolders
        For Each subfolder in objFolder.SubFolders
            WScript.Echo subfolder.Size
    Next
Next

You might want to skip through the folders that you are not authorized to access. Hence the first statement.

Upvotes: 0

Bond
Bond

Reputation: 16311

For Each objFolder In objFSO.GetFolder("C:\").SubFolders
    WScript.Echo objFolder.Path
Next

' or...

For Each objFolder In objFSO.GetDrive("C:").RootFolder.SubFolders
    WScript.Echo objFolder.Path
Next

Edit: sundar nataraj Сундар has asked that I go into more detail.

This is a basic For loop that iterates the SubFolders collection. The SubFolders property is only available for a Folder object. You can get a Folder object for the root in a number of ways. Here are two examples:

  1. Use the GetFolder() function to retrieve a root folder.
  2. Use the RootFolder property of a Drive object.

I've added a WScript.Echo statement in each example to demonstrate the use of the objFolder variable.

Upvotes: 8

Related Questions