VBScript to move file with wildcard, if it exists

落花浮王杯 提交于 2019-12-01 08:48:05
Ahmad El-Hoss

You can replicate a wild card search by using a combination of instr() and right(), or just multiple instr().

Set objFSO = CreateObject("Scripting.FileSystemObject")
objStartFolder = "d:\eventlogs\"

Set objFolder = objFSO.GetFolder(objStartFolder)

Set colFiles = objFolder.Files
For Each objFile in colFiles
   if instr(objFile.Name,"Archive") <> 0 AND instr(objFile.Name,".evtx") <> 0 then
       objFSO.MoveFile objFile.Name, "archive\" + objFile.Name
   end if
Next

The appropriate approach of finding files with wildcards in VBScript:

  1. Get the file collection from the containing folder
  2. For each file in the filecollection:
  3. Test the filename with a regular expression on a certain pattern
  4. If the test passes, do some action with this file
  5. Next file

Late answer, but might be useful because apparently nobody spotted the mistake.

From the VBScript documentation (script56.chm in my case), help page for CopyFile method says:

FileExists Method

Returns True if a specified file exists; False if it does not.

object.FileExists(filespec)

Arguments

object

Required. Always the name of a FileSystemObject.

filespec

Required. The name of the file whose existence is to be determined. A complete path specification (either absolute or relative) must be provided if the file isn't expected to exist in the current folder.

Hence your expression fso.FileExists("d:\eventlogs\Archive*.evtx") returns False here; indeed there isn't any file named Archive*.evtx in your folder.

Either you remove your test, but you'll have to deal with the error the CopyFile method might generate, as doc says:

An error also occurs if a source using wildcard characters doesn't match any files.

As suggested by @automatedchaos in his answer https://stackoverflow.com/a/20907209/666414 you can also loop through files of the folder and decide what to do whenever the filename/extension matches your pattern.

Lastly, you can mix both solutions: loop through files of the folder, then set a flag to True and Exit Loop as soon as you encounter an expected file, then use the CopyFile method.

Like this:

With CreateObject("Scripting.FileSystemObject")
    For Each objFile in .GetFolder("d:\eventlogs\").Files
        If Left(objFile.Name, 7) = "Archive" And .GetExtensionName(objFile) = "evtx" Then
            archiveFound = True
        End If
    Next

    If archiveFound Then
        .CopyFile "d:\eventlogs\Archive*.evtx", "d:\eventlogs\archive\"
        .DeleteFile "d:\eventlogs\Archive*.evtx"
    End If
End With

Note the wildcards work with the DeleteFile method too!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!