VBScript – Scan and Replace a String in Text File

email me

I’m using this to do a simple setting replacement in a config file. It won’t matter which line it is on, and…it won’t matter if you only know part of the string.

'Option Explicit
On error resume next

dim objFSO, strFolder, strFilePath, tmpFile, strLineInput, Settings

Const ForReading = 1

Const ForWriting = 2

Set objFSO = CreateObject("Scripting.FileSystemObject")

strFolder = "C:\ProgramData\ABC_Program\"

strFilePath = strFolder & "TheFile.ini"

Set Settings = objFSO.OpenTextFile(strFilePath, ForReading, True)

Set tmpFile = objFSO.OpenTextFile(strFilePath & ".tmp", ForWriting, True)

Do While Not Settings.AtEndofStream

strLineInput = Settings.ReadLine

If InStr(strLineInput, "AutoUpdate=") Then

strLineInput = "AutoUpdate=0"

End If

tmpFile.WriteLine strLineInput

Loop

Settings.Close

tmpFile.Close

objFSO.DeleteFile(strFilePath)

objFSO.MoveFile strFilePath&".tmp", strFilePath


Notes

on error resume next 

Const ForReading = 1

Const ForWriting = 2

Set objFSO = CreateObject("Scripting.FileSystemObject")

Set objShell = WScript.CreateObject("WScript.Shell")

Set objFile = objFSO.OpenTextFile("C:\IEZoneSettings.reg", ForReading)


strUser = objShell.ExpandEnvironmentStrings("%USERNAME%")

strText = objFile.ReadAll

objFile.Close

strNewText = Replace(strText, "XXXXX", strUser)


Set objFile = objFSO.OpenTextFile("C:\IEZoneSettings.reg", ForWriting)

objFile.WriteLine strNewText

objFile.Close