在vbs中查找并替换多个文件

时间:2012-02-02 20:20:28

标签: vbscript

我正在尝试使用vbs脚本实现对文件夹中所有文件的查找和替换,这是我到目前为止所拥有的

Dim fso,folder,files,oldFileContents,newFileContents,FIND,REPLACE

FIND = "textToBeReplaced"
REPLACE = "localhost"

Set fso = CreateObject("Scripting.FileSystemObject")

Set folder = fso.GetFolder("HTML")
Set files = folder.Files

For each item In files
    oldFileContents = GetFile(item.Path)
    newFileContents = replace(oldFileContents,FIND,REPLACE,1,-1,1)
    WriteFile FileName,newFileContents
Next

但是当我尝试运行它时,我得到并且错误,“类型不匹配:'GetFile'”,我做错了什么?

2 个答案:

答案 0 :(得分:3)

问题应该通过以下代码解决:

' Constants Mr Gates forgot (but cf. vbTextCompare)
  Const ForReading = 1
  Const ForWriting = 2
' Configuration constants  
  Const csFind     = "pdf"
  Const csRepl     = "puf"
' Dim & init for vars needed on *this* level   
  Dim oFS   : Set oFS = CreateObject("Scripting.FileSystemObject")
  Dim sTDir : sTDir   = oFS.GetAbsolutePathName("..\data\test")
  Dim oFile
  For Each oFile In oFS.GetFolder(sTDir).Files
      WScript.Echo "looking at", oFile.Name
      ' Dim & init for vars needed on *this* level   
      Dim sContent : sContent = goFS.GetFile(oFile.Path)
      ' For Skytunnels and other air-coders
      WScript.Echo "content is not", sContent
      ' you got oFile, so use it; no need for .GetFile()
      sContent = oFile.OpenAsTextStream(ForReading).ReadAll()
      WScript.Echo "qed! content is", sContent
      ' Replace(expression, find, replacewith[, start[, count[, compare]]])
      ' don't use magic numbers; vbTextCompare is even pre-defined
      sContent = Replace(sContent, csFind, csRepl, 1, -1, vbTextCompare)
      WScript.Echo "new content", sContent
      oFile.OpenAsTextStream(ForWriting).Write sContent
      sContent = oFile.OpenAsTextStream(ForReading).ReadAll()
      WScript.Echo "new content straight from file", sContent
      WScript.Echo "------------------"
  Next

输出:

...
------------------
looking at 0000000000012345.20120302.pdf
content is not E:\trials\SoTrials\answers\9117277\data\test\0000000000012345.20120302.pdf
qed! content is This is the content of 0000000000012345.20120302.pdf

new content This is the content of 0000000000012345.20120302.puf

new content straight from file This is the content of 0000000000012345.20120302.puf

重点:

  1. 不要在脚本顶部使用Dim-all-vars-used-used-line
  2. 避免创建不必要的变量(文件夹,文件,*内容),使用 你有正确的变量(item == oFile)
  3. .GetFile()返回File对象,而不是文件的内容

答案 1 :(得分:1)

你错过了fso.

oldFileContents = fso.GetFile(item.Path)

fso.WriteFile FileName,newFileContents

编辑:根据下面的讨论,请注意这个答案仅用于显示您的错误发生的位置。我们假设您的意图是在您遇到此错误后进一步开发代码,如果是这样,我相信您已经看到Ekkehard已经为他的答案提供了一些非常有用的指导。