How to list the top level folders of a drive using VBScript?
6,234
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.
Author by
lewisc
Updated on September 18, 2022Comments
-
lewisc over 1 year
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
-
gWaldo over 12 yearsYou should post an answer and mark it closed.
-