如何使用VBscript使用通配符查找和读取文件?

时间:2015-10-27 06:49:57

标签: file vbscript io

我尝试读取XML文件失败(文件名在每台计算机中都有变化)。 如何使用外卡读取文件?
例如:D:\Logs\*.xml

脚本:

Const ForReading = 1
Const ForWriting = 2
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("D:\Logs\*.xml", ForReading)
strText = objFile.ReadAll
objFile.Close
strNewText = Replace(strText, "server1 ", "server889 ")
Set objFile = objFSO.OpenTextFile("D:\Logs\*.xml", ForWriting)
objFile.WriteLine strNewText
objFile.Closeenter code here

1 个答案:

答案 0 :(得分:4)

VBScript中没有外卡。对由Files方法获得的Folder GetFolder对象集合中的每个元素重复一组语句:

Const ForReading = 1
Const ForWriting = 2
Set objFSO = CreateObject("Scripting.FileSystemObject")

Set objFolder = objFSO.GetFolder("D:\Logs")

Set colFiles = objFolder.Files
For Each oFile in colFiles
    If UCase(objFSO.GetExtensionName(oFile.name)) = "XML" Then
        Set objFile = objFSO.OpenTextFile(oFile.Path, ForReading)
        strText = objFile.ReadAll
        objFile.Close
        If Instr( 1, strText, "server1 ", vbTextCompare) > 0 Then
            strNewText = Replace(strText, "server1 ", "server889 ", 1, -1, vbTextCompare)
            Set objFile = objFSO.OpenTextFile(oFile.Path, ForWriting)
            objFile.WriteLine strNewText
            objFile.Close
        End If
    End If
Next

资源:FileSystemObject