Tuesday, February 7, 2017

VBScript Append text to text file if it already exists

Option Explicit

Const ForReading = 1, ForAppending = 8

Dim InputFileName, OutputFileName, FileSystemObject, InputFile, OutputFile

Set FileSystemObject = CreateObject("Scripting.FileSystemObject")
InputFileName  = "C:\tmp\input.txt"
OutputFileName = "C:\tmp\output.txt"

PreCheck

Set InputFile = FileSystemObject.OpenTextFile(InputFileName, ForReading)
Set OutputFile = FileSystemObject.OpenTextFile(OutputFileName, ForAppending, True)

OutputFile.WriteLine ""
Do While Not InputFile.AtEndOfStream 
    OutputFile.WriteLine InputFile.ReadLine
Loop

InputFile.Close
OutputFile.Close

Sub Echo(Str)
    Wscript.Echo Str
End Sub

Sub PreCheck()
    If Not FileSystemObject.FileExists(OutputFileName) Then
        Echo "Output File Not Found"
        WScript.Quit
    End If

    If Not FileSystemObject.FileExists(InputFileName) Then
        Echo "Input File Not Found"
        WScript.Quit
    End If

    If FileSystemObject.GetFile(InputFileName).Size < 1 Then
        Echo "Input File Has No Content"
        WScript.Quit
    End If
End Sub

No comments:

Post a Comment