WMI查询在查询Win32_Directory时返回null集合

时间:2014-08-18 20:52:30

标签: csv vbscript wmi wql

我正在尝试使用VBScript选择特定文件夹中的所有csv,然后将它们连接成一个。我正在使用Win32_Directory上的ExecQuery将所有csv添加到集合中,指定路径和扩展属性。我在要测试的文件夹中有五个csv。但是返回的集合总是为空。

这是我的代码:

strComputer = "."
Set wshShell = WScript.CreateObject( "WScript.Shell" )
Set objWMIService = GetObject("winmgmts:" _
   & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

'Options for CreateTextFile
boolOverwrite = True
boolUnicode = True

'Options for OpenTextFile
constForReading = 1
constForWriting = 2
constForAppending = 8
boolCreate = False
constTristate = -1

strPath = "C:\Users\adam\Documents\Test\Temp.csv"
strDrivePath = "C:\Users\adam\Documents\Test"

'Creates object reference to files in relevant folder.
Set objFSO = CreateObject ("Scripting.FileSystemObject")

'Creates new CSV to write others' contents to.
Set objNew = objFSO.CreateTextFile(strPath,boolOverwrite,boolUnicode)

Set colCSV = objWMIService.ExecQuery _
 ("SELECT * FROM Win32_Directory WHERE Path = strDrivePath AND Extension = 'csv'")

'Concatenates contents of CSVs
For Each objCSV in colCSV
 Set objTemp = objFSO.OpenTextFile(objCSV.Path & objCSV.FileName & objCSV.Extension,constForReading,boolCreate,constTristate)
 Set strLine = objTemp.ReadLine
 objNew.Write strLine 

Next

我也不确定我为OpenTextFile指定路径的方式是否有效。但我现在主要担心的是让查询返回我想要的文件。

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

你在这里遇到了一些问题。

  1. 如果要选择文件,请使用CIM_DataFile类。你猜对了Win32_Directory目录。

  2. Path属性中的反斜杠必须转义(\\)。

  3. strDrivePath是一个变量,但您在WMI查询中确实使用它。

  4. 您打算在远程计算机上运行此脚本吗?如果没有,为什么不使用FileSystemObject方法?您已经创建了FSO对象。

  5. Here是我过去回答的类似问题,展示了如何使用FileSystemObject或WMI查询来查找符合规范的文件。

    在这种情况下,您的查询可能如下所示:

    strFileSpec = "C:\\Users\\Adam\\Documents\\Test\\%.csv"
    
    Set colCSV = objWMIService.ExecQuery _
     ("select * from CIM_DataFile where Name like '" & strFileSpec & "'")
    

    但是,如果在语句中指定DrivePath的值,则查询运行速度会更快(通常会显着)。有关示例,请参阅我的链接帖子。

    编辑:我刚刚意识到你是我所链接的问题的OP!

相关问题