How can I use VBScript to insert a line into a text file?

John Savill

August 10, 2005

1 Min Read
ITPro Today logo in a gray background | ITPro Today

A. VBScript has no built-in functionality that lets you insert a line into a file. The simplest way to do that is to open the file you want to insert a line into, write the file line by line to a new file, and insert the new line where you want it. I wrote the following script, which you can download at http://www.windowsitpro.com/content/content/47437/insertfile.zip, to insert a line into a sysprep.inf file in the [Unattended] section. (Some lines wrap because of space constraints.)

Option ExplicitDim strFileSourcePath, strFileTargetPath, objFSOSource, objFSOTarget, fso, objFilesSource, objFilesTarget, strCurrentLineConst ForReading = 1, ForWriting = 2strFileSourcePath = "C:sysprepsysprep.inf"strFileTargetPath = "C:sysprepsysprep.new"Set objFSOSource = CreateObject("scripting.filesystemobject")Set objFSOTarget = CreateObject("scripting.filesystemobject")Set objFilesSource = objFSOSource.OpenTextFile(strFileSourcePath,ForReading,True,0) Set objFilesTarget = objFSOSource.OpenTextFile(strFileTargetPath,ForWriting,True,0) Set fso = CreateObject("Scripting.FileSystemObject")Do While objFilesSource.AtEndOfStream  True  strCurrentLine = objFilesSource.ReadLine  if StrComp(Left(strCurrentLine,12),"[Unattended]") = 0 then    objFilesTarget.WriteLine strCurrentLine    objFilesTarget.WriteLine "OemPnPDriversPath = xpdriversetwork; xpdriversstorage; xpdriversVideo"  else    objFilesTarget.WriteLine strCurrentLine  end ifLoopobjFilesSource.CloseobjFilesTarget.CloseSet objFSOSource = NothingSet objFSOTarget = Nothingfso.MoveFile "C:sysprepsysprep.inf", "C:sysprepsysprep.old"fso.MoveFile "C:sysprepsysprep.new", "C:sysprepsysprep.inf"Set fso = Nothing 

The script reads each line from the existing sysprep.inf and writes it to sysprep.new. It checks the first 12 characters of each line looking for the characters "[Unattended]" (not including quotation marks}. When the script finds a line in which the first 12 characters are "[Unattended]", it writes the current line, then writes the new content (in my case a OemPnPDriversPath entry). At the end of the execution, the script renames the existing file with an .old file extension (i.e., sysprep.old) and renames the newly created file with an .inf file extension (i.e., sysprep.inf).

About the Author

Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like