65.9K
CodeProject is changing. Read more.
Home

Replace parameters with values in text file with VBScript

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0 vote)

Feb 9, 2010

CPOL
viewsIcon

17486

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

' 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"