Udostępnij za pośrednictwem


Scripting: How to edit an INI file from a script

I was asked how to modify an INI from a script.  Its quite straight forward.  Firstly have a read of the Scripting Guy article here.  It explains the process quite well actually.  However, I wanted to go a step further and setup arguments to make the script re-useable.  So here is the modified script:

'Usage: modini.vbs <full path to ini>, Parameter to change, New Value
'Example: modini.vbs c:\folder\my.ini, Script, change

Const ForReading = 1
Const ForWriting = 2

strINIFile = WScript.Arguments.Item(0)
strParam = WScript.Arguments.Item(1)
strValue = WScript.Arguments.Item(2)

If WScript.Arguments.Count <> 3 Then WScript.Quit

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.OpenTextFile(strINIFile, ForReading)

Do Until objTextFile.AtEndOfStream
strNextLine = objTextFile.Readline

    intLineFinder = InStr(strNextLine, strParam)
If intLineFinder <> 0 Then
strNextLine = strParam & "=" & strValue
End If

    strNewFile = strNewFile & strNextLine & vbCrLf
Loop

objTextFile.Close

Set objTextFile = objFSO.OpenTextFile(strINIFile, ForWriting)

objTextFile.WriteLine strNewFile
objTextFile.Close

Here is a sample batch file calling the VBS script:

cscript //nologo modini.vbs "c:\my.ini" "Blog" "sometimes"

And thats it!  Short and sweet.