Rehana Sultana
Rehana Sultana

Reputation: 49

Can somebody correct the vbscript error

I'm trying to copy of all the order files into one file at the end of the day. Here's my code.Can somebody please correct the error.The error is in cFol when I type in the complete name of the directory like C:\Customers\ABF\Orders I'm not getting any error. But when I give cFol I'm getting an error 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

The error occurs in this line:

Set FileList = objWMIService.ExecQuery _
  ("ASSOCIATORS OF {Win32_Directory.Name='cFol'} Where " _
  & "ResultClass = CIM_DataFile")

Upvotes: 0

Views: 873

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200503

VBScript doesn't expand variable name inside strings, so your WMI query is looking for a directory with the name cFol, which doesn't exist. Also, you probably need to escape backslashes in the path. Replace this:

Set FileList = objWMIService.ExecQuery _
  ("ASSOCIATORS OF {Win32_Directory.Name='cFol'} Where " _
  & "ResultClass = CIM_DataFile")

with this:

Set FileList = objWMIService.ExecQuery _
  ("ASSOCIATORS OF {Win32_Directory.Name=""" & Replace(cFol, "\", "\\") _
  & """} Where ResultClass = CIM_DataFile")

and the error should disappear.

As a safety precaution, I also replaced the single quotes with double quotes. While single quotes are valid string delimiters in WMI, they're alsow valid characters in file and folder names, so you could run into problems when you have a path that contains a single quote. Using double quotes avoids this issue, because they're not valid characters for file and folder names.

Upvotes: 2

Related Questions