我正在尝试在一天结束时将所有订单文件复制到一个文件中。这是我的代码。可以请有人纠正错误。错误在cFol
当我输入像C:\Customers\ABF\Orders
这样的目录的完整名称时,我没有收到任何错误。但是当我提出cFol
时,我收到了错误0x80041002
。
showfolderlist "c:\Customers"
Sub ShowFolderList(folderspec)
Dim fs, f, f1, fc, s
s = ""
Set fs = CreateObject("Scripting.FileSystemObject")
Set f = fs.GetFolder(folderspec)
Set fc = f.SubFolders
For Each f1 in fc
s = f1.name
Msgbox s
Const ForReading = 1
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objOutputFile = objFSO.CreateTextFile("C:\New\output.txt")
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
cFol = "C:\Customers\" & s & "\Orders"
msgbox cFol
Set FileList = objWMIService.ExecQuery _
("ASSOCIATORS OF {Win32_Directory.Name='cFol'} Where " _
& "ResultClass = CIM_DataFile")
For Each objFile In FileList
Set objTextFile = objFSO.OpenTextFile(objFile.Name, ForReading)
strText = objTextFile.ReadAll
objTextFile.Close
objOutputFile.WriteLine strText
Next
objOutputFile.Close
s=""
Next
End Sub
此行发生错误:
Set FileList = objWMIService.ExecQuery _
("ASSOCIATORS OF {Win32_Directory.Name='cFol'} Where " _
& "ResultClass = CIM_DataFile")
答案 0 :(得分:2)
VBScript不会在字符串中扩展变量名,因此您的WMI查询正在查找名称为cFol
的目录,该目录不存在。此外,您可能需要在路径中转义反斜杠。替换这个:
Set FileList = objWMIService.ExecQuery _
("ASSOCIATORS OF {Win32_Directory.Name='cFol'} Where " _
& "ResultClass = CIM_DataFile")
用这个:
Set FileList = objWMIService.ExecQuery _
("ASSOCIATORS OF {Win32_Directory.Name=""" & Replace(cFol, "\", "\\") _
& """} Where ResultClass = CIM_DataFile")
并且错误应该消失。
作为安全预防措施,我还用双引号替换了单引号。虽然单引号是WMI中的有效字符串分隔符,但它们在文件和文件夹名称中也是有效字符,因此当您拥有包含单引号的路径时,可能会遇到问题。使用双引号可以避免此问题,因为它们不是文件和文件夹名称的有效字符。