Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Replace parameters with values in text file with VBScript

0.00/5 (No votes)
3 May 2010 1  
Introduction...

Introduction


Here is a VBScript code that replaces values in the original text file and saves results in the destination text file.

This code can be helpful for creating parametrized scripts/schemes/input for applications that don't accept parameters in the command line.

Code


VBScript
' Replace.vbs
'--------------------------------------------------
'	Sub Main
'--------------------------------------------------
Dim FileName, FileName2, Find, ReplaceWith, FileContents, dFileContents
Find         = WScript.Arguments(0)
ReplaceWith  = WScript.Arguments(1)
FileName     = WScript.Arguments(2)
FileName2    = WScript.Arguments(3)

FileContents = GetFile(FileName)

dFileContents = Replace(FileContents, Find, ReplaceWith, 1, -1, 1)

if dFileContents <> FileContents Then
  WriteFile FileName2, dFileContents
Else
  Wscript.Echo "Searched string Not In the source file"
End If
'--------------------------------------------------
'	Function GetFile
'--------------------------------------------------
function GetFile(FileName)
  If FileName<>"" Then
    Dim FS, FileStream
    Set FS = CreateObject("Scripting.FileSystemObject")
      on error resume Next
      Set FileStream = FS.OpenTextFile(FileName)
      GetFile = FileStream.ReadAll
  End If
End Function
'--------------------------------------------------
'	Function WriteFile
'--------------------------------------------------
function WriteFile(FileName, Contents)
  Dim OutStream, FS

  on error resume Next
  Set FS = CreateObject("Scripting.FileSystemObject")
    Set OutStream = FS.OpenTextFile(FileName, 2, True)
    OutStream.Write Contents
End Function


Using the Script


cscript Replace.vbs [CurrentDate] 20100208 "GenericScript.txt" "CurrentScript.txt"


If you want to replace several parameters, you will need to call this script more than once, but having the source file name same as destination file name:

cscript Replace.vbs [CurrentCampaign] DFD435SF "CurrentScript.txt" "CurrentScript.txt"

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here