Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

I'm looking for VBScript code that will list the top level folders of the D: drive and not the subfolders. I use the following WMI query so far but it gives me all folders and goes down to many levels. Also seems to just stop for a reason I have not determined just yet.

Set colFolders = objWMIService.ExecQuery("Select * from Win32_Directory Where Drive = 'D:'")

EDIT:

After more searching I found something that gives me what I wanted. Just in case there are others looking here is the VBScript for folders and size:

Set objFSO = WScript.CreateObject("Scripting.FileSystemObject")
set objFolder = objFSO.GetFolder("D:\")
for Each folder in objFolder.SubFolders
    On Error Resume Next
    size = folder.size
    if Err.Number <> 0 Then
        size = -1
    end if
    wscript.echo folder.name,size
Next
share|improve this question
3  
You should post an answer and mark it closed. –  gWaldo Aug 19 '11 at 16:07

1 Answer 1

To specify that you want only the top-level folders, you need to add the Path = '\\' condition to the WHERE clause:

strComputer = "."
Set oWMI = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2")

Set colFolders = oWMI.ExecQuery _
    ("SELECT * FROM Win32_Directory WHERE Drive = 'D:' AND Path = '\\' ",, 48)

For Each oFolder In colFolders
    WScript.Echo oFolder.Name
Next

Alternatively, you can use an ASSOCIATORS OF query to get the top-level folders as subfolders of the drive root:

strComputer = "."
Set oWMI = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")

Set colFolders = oWMI.ExecQuery _
    ("ASSOCIATORS OF {Win32_Directory.Name='D:\'} " _
        & "WHERE AssocClass = Win32_Subdirectory " _
            & "ResultRole = PartComponent",, 48)

For Each oFolder In colFolders
    WScript.Echo oFolder.Name
Next

But the FileSystemObject solution is probably easier.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.