Replace text in a text file from the command line using a vbs script

codeThere is a need to replace a value from within a text based file from one variable to another using a command line approach, as everything else in that process was automated. There is however, no native command line support within the Microsoft Windows environment that would allow for this to be accomplished. Someone in the Microsoft forums had written, what appears to be a simple visual basic script that will search and replace all instances of one variable to another variable.

Replace.vbs code

Const ForReading = 1
Const ForWriting = 2

strFileName = Wscript.Arguments(0)
strOldText = Wscript.Arguments(1)
strNewText = Wscript.Arguments(2)

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(strFileName, ForReading)

strText = objFile.ReadAll
strNewText = Replace(strText, strOldText, strNewText)

Set objFile = objFSO.OpenTextFile(strFileName, ForWriting)
objFile.WriteLine strNewText


After saving the above code to a file called replace.vbs, use the script in the following syntax. In this example, I want to replace the “&” character in the fzdefaults.xml file.

cscript replace.vbs "fzdefaults.xml" "&" "&"