![如何使用 VBScript 列出驱动器的顶层文件夹?](https://linux22.com/image/559085/%E5%A6%82%E4%BD%95%E4%BD%BF%E7%94%A8%20VBScript%20%E5%88%97%E5%87%BA%E9%A9%B1%E5%8A%A8%E5%99%A8%E7%9A%84%E9%A1%B6%E5%B1%82%E6%96%87%E4%BB%B6%E5%A4%B9%EF%BC%9F.png)
我正在寻找 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
解决办法可能更简单。