如何使用 VBScript 列出驱动器的顶层文件夹?

如何使用 VBScript 列出驱动器的顶层文件夹?

我正在寻找 VBScript 代码,该代码将列出 D: 驱动器的顶级文件夹而不是子文件夹。到目前为止,我使用以下 WMI 查询,但它给出了所有文件夹并向下延伸到多个级别。而且似乎只是因为我尚未确定的原因而停止了。

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

编辑:

经过更多搜索,我找到了我想要的东西。为了以防其他人也在寻找,这里是用于文件夹和大小的 VBScript:

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

答案1

要指定只想要顶级文件夹,您需要Path = '\\'WHERE子句中添加条件:

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

或者,您可以使用ASSOCIATORS OF查询来获取顶级文件夹作为驱动器根目录的子文件夹:

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

FileSystemObject解决办法可能更简单。

相关内容