Perform In-Place file edit with VBScript

Recently had the need to search and replace a configuration file on a system. This was part of an installation of an older program that required a variable to be replace with the computername. Being that the systems were Windows of several different releases (2000, 2003 and 2008) I could not use Powershell to complete the task and went with vbscript as the tool of choice.

Here is what the script looks like. In this example I am editing the config.ini file and looking for WIN01 and replacing it with the computername.

The script can be broken done into several sections.

  • define constants
  • set objects
  • set variables
  • do the work
  • close it up

For define constants we need to define the file for Reading and Writing and also define the input and output file.

There are three File input / output constants available as shown in the table below.

Constant Value Description
ForReading 1 Open a file for reading only. No writing to this file can take place.
ForWriting 2 Open a file for writing. If a file with the same name exists, its previous contents are overwritten.
ForAppending 8 Open a file and write to the end of the file.

For FileIn and FileOut we just need to put the location and name of the file we want to edit.

Next we need to set the file system object , set the File object and set the shell environment.

Now we want to create a variable called strComputer and get the Environment variable for %COMPUTERNAME%.

Next we need to open the file we want to edit into memory and then create a variable for finding and replacing the replacement text.

And finally, lets write the changes to the file.

And that’s all there is to editing a file in place with vbscript. Hope you find this useful to your situation.


Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.