RSS

VBScript: comparing two files using dictionary object

06 May

Here is a VBScript function to compare 2 files and get the changes between them. The function will return a multi-line string with what was added, modified and deleted between the old and new file.

This function was initially developed for me to compare changes between an old and new input file in my script. I need to know which server was added or removed and which server had its parameters modified. The input files is a delimited file using “~” as a delimiter and contains 2 values in each line: “server name” & “parameter”.

This will help explain why the code was written the way it is. You can use this and change according to what you require.  Some of you may cringe that the liberal use of single letter variables, I have my own thoughts about this on the readability versus efficiently in short programming codes

Apologise for the bad formatting, wordpress is not the best place to show programming codes..

Function Get_FileDiff(pFileOld, pFileNew)
dim fso, t, txt
dim d1, d2, i, k
Get_FileDiff = ""
Set fso = CreateObject("Scripting.FileSystemObject")
if fso.FileExists(pFileOld) and fso.FileExists(pFileNew) then
  Set d1 = CreateObject("Scripting.Dictionary") 'old file contents
  Set d2 = CreateObject("Scripting.Dictionary") 'new file contents
  set txt = fso.OpenTextFile(pFileOld, 1)
  do while not txt.AtEndOfStream
    t = split(ucase(txt.readline),"~")
    d1.Add t(0), t(1)
  loop
  txt.close
  set txt = fso.OpenTextFile(pFileNew, 1)
  do while not txt.AtEndOfStream
    t = split(ucase(txt.readline),"~")
    d2.Add t(0), t(1)
  loop
  txt.close
  k = d1.keys
  for i = 0 To d1.Count -1 ' Iterate the array.
    if not d2.Exists(k(i)) then
      Get_FileDiff = Get_FileDiff & "deleted: " & k(i) & vbCrLf
    else
      if d1(k(i)) <> d2(k(i)) then
        Get_FileDiff = Get_FileDiff & "modified: " & k(i) _
        & ": old=" & d1(k(i)) & ",new=" & d2(k(i)) _
        & vbCrLf
      end if
    end if
  next
  k = d2.keys
  for i = 0 To d2.Count -1 ' Iterate the array.
    if not d1.Exists(k(i)) then _
    Get_FileDiff = Get_FileDiff & "added: " & k(i) & vbCrLf
  next
else
  Get_FileDiff = "error: One of the files: " & pFileOld & " or " _
  & pFileNew & " not found!"
end if
set fso = Nothing
End Function
Advertisements
 
Leave a comment

Posted by on May 6, 2011 in Scripts, VBScripts

 

Tags:

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: