Thursday, September 10, 2009

How to Edit an INI file using VBScript

Modify the highlighted sections with the appropriate changes.

Note that you can use environment variables to ensure that it will work on all systems. eg. If you use %SystemRoot% it will work whether windows is installed in C:\WINNT or D:\Windows.

' This script can be used to edit entries in ini files
' Written by Sean Bradley
' Version 1.0
' Last modified 11/09/09
Const ForReading = 1
Const ForWriting = 2
Set oShell = CreateObject( "WScript.Shell" )

'Set the target file and backup directory.
'Note that I've used an environment variable here to ensure it works on all systems.
targfile=oShell.ExpandEnvironmentStrings("%SystemRoot%") + "\editthisfile.ini"
backdir=oShell.ExpandEnvironmentStrings("%TEMP%") + "\"
Set objFSO = CreateObject("Scripting.FileSystemObject")

'Make sure the file exists to prevent errors.
if objFSO.FileExists(targfile) then
'Copy it to the backup directory then open the file.
objFSO.CopyFile targfile, backdir, true
Set objTextFile = objFSO.OpenTextFile(targfile, ForReading)

'Read through each line of the file for the entry you want to set
Do Until objTextFile.AtEndOfStream
strNextLine = objTextFile.Readline
intLineFinder = InStr(strNextLine, "IniFileEntrytoEdit")
If intLineFinder <> 0 Then

'Set your new entry here.
strNextLine = "IniFileEntrytoEdit=My Entry in the File"
End If
strNewFile = strNewFile & strNextLine & vbCrLf


'Write the file with the new entry
Set objTextFile = objFSO.OpenTextFile(targfile, ForWriting)

objTextFile.WriteLine strNewFile
End If