Dehardcode/replace string in files with VBScript

During the packaging of a certain application, there might be cases where a specific configuration file must contain some dynamic settings. For example, let’s assume that you need to write a specific IP, or a specific location in a config.txt file during installation, and let’s assume the configuration file has the following contents:

[config]

IP=192.168.0.1
INSTALLLOCATION=C:\PROGRAM FILES(X86)\TEST APPLICATION
BASECONFIGURATION=My Configuration 1

 

Now, let’s see how we can dynamically write the INSTALLLOCATION and BASECONFIGURATION parameters. In this example, we want to change the INSTALLLOCATION to C:\Program Files(x86)\MyApplication, and BASECONFIGURATION to My Configuration 2.
For this, the following VBScript can be added in your MSI:

 

Dim objFSO
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set oWSH = CreateObject("WScript.Shell")
Const ForReading = 1, ForWriting = 2, ForAppending = 8
Dim strFilePath, strToReplace, strNewValue, path1, path2

strFileLocation = oWSH.ExpandEnvironmentStrings("%ProgramFiles(x86)%")
path1 = strFileLocation & "\MyApplication\"


MyConfig = "My Configuration 2"


Function ReplaceInFile(strToReplace, strNewValue, strFilePath)

Dim objFile, strText, re
Set objFSO = CreateObject("Scripting.FileSystemObject")
if objFSO.FileExists(strFilePath) Then
Set objFile = objFSO.OpenTextFile(strFilePath, ForReading, True)
strText = objFile.ReadAll
objFile.Close
Set objFile = Nothing

strText = Replace(strText, strToReplace, strNewValue, 1, -1, 0)

Set objFile = objFSO.CreateTextFile(strFilePath, True)
objFile.Write strText
objFile.Close
Set objFile = Nothing

End If

Set objFSO = Nothing

End Function

strToReplace = "My Configuration 1"
strNewValue = MyConfig
ReplaceInFile strToReplace, strNewValue, path1 & "Config.txt"

strToReplace = "C:\PROGRAM FILES(X86)\TEST APPLICATION"
strNewValue = path1
ReplaceInFile strToReplace, strNewValue, path1 & "Config.txt"

 

As you can see from the code above, the ReplaceInFile function takes three parameters:

  1. The string we are replacing in the file, basically the string we are going to search for
  2. The new string which is going to replace the previously searched string
  3. The location of the file

The function opens up the file, searches for the string to replace (strToReplace), and replaces it with the new value (strNewValue). You can search and replace for multiple strings as you can see from the bottom of the script.

Sharing is caring!

Leave a comment

Your email address will not be published. Required fields are marked *

two × five =