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

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, to insert a line into a sysprep.inf file in the \[Unattended\] section. (Some lines wrap because of space constraints.)

Option Explicit

Dim strFileSourcePath, strFileTargetPath, objFSOSource, objFSOTarget, fso, objFilesSource, objFilesTarget, strCurrentLine

Const ForReading = 1, ForWriting = 2

strFileSourcePath = "C:\sysprep\sysprep.inf"
strFileTargetPath = "C:\sysprep\"

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 = xpdrivers\network; xpdrivers\storage; xpdrivers\Video"
    objFilesTarget.WriteLine strCurrentLine
  end if



Set objFSOSource = Nothing
Set objFSOTarget = Nothing

fso.MoveFile "C:\sysprep\sysprep.inf", "C:\sysprep\sysprep.old"
fso.MoveFile "C:\sysprep\", "C:\sysprep\sysprep.inf"

Set fso = Nothing
The script reads each line from the existing sysprep.inf and writes it to 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).
Hide comments


  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.