Click here to Skip to main content
15,891,943 members
Articles / Programming Languages / VBScript
Tip/Trick

Replace parameters with values in text file with VBScript

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
3 May 2010CPOL 17.1K   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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Database Developer
United Kingdom United Kingdom
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --