Thursday, 6 February 2014

VBScript - Simple String Comparison script

When we have two strings to compare, it can be useful to have a little helper script to do the comparing for us and make sure the strings really do or do not match.

A good example of this is when we’re comparing Hashes / Checksums, as described in a previous post: http://cyreath.blogspot.co.uk/2014/02/file-hashes-checksums-easy-way-to-check.html

In the VBSCript script below we have a way to do a comparison and see what the results are. Let’s walk through it.



YouTube Channel: [WATCH, RATE, SUBSCRIBE]


First we do the usual declaration and assignment of variables, always using Option Explicit to make sure we don’t introduce errors as we go.

Option Explicit

Dim sTitle, sPrompt, sStringFormat, sFirstString, sSecondString, sResult

sTitle = "String Comparison"
sPrompt = "Enter the strings you want to compare"


Then we ask the user for the two string they want to do a comparison on

'Get the strings to compare
sFirstString = InputBox(sPrompt, sTitle)
sSecondString = InputBox(sPrompt, sTitle)


If the strings are a different case, VBScript will tell us they are different when compared. Therefore we need to make sure the strings are the same case. Here we just ask the question, we’ll change the case in the If statement to follow.

'Check if the string's case should match or stay as they are
sStringFormat = MsgBox("Change case to match?", vbYesNoCancel+vbQuestion+vbDefaultButton2+vbSystemModal, sTitle)


Here’s where we act on the input, changing case if the user said to do so. Reading through you’ll see we’re using StrComp () to do the comparison for us.

'Check the input and either leave the strings case as is or convert them both to lowercase
If sStringFormat = vbNo Then
        sResult = StrComp(sFirstString,sSecondString)
       
        ElseIf  sStringFormat = vbYes Then
               sFirstString = LCase(sFirstString)
               sSecondString= LCase(sSecondString)
               sResult = StrComp(sFirstString,sSecondString)
              
        Else    MsgBox ("Looks like you hit Cancel")

End If


In this script, we have some tests to make sure it’s working. You can delete these lines as they’re not needed once we’re confident in the script.

MsgBox ("First string is " & sFirstString) 'test
MsgBox ("Second string is " & sSecondString) 'test
MsgBox ("sResult is " & sResult) 'test


Once done, we display the results of the comparison

        'Stating if the strings match
        If sResult = 0 Then 'strings match then we're OK
               MsgBox ("The two strings DO match")

        Else ' Anything else is a fail
               MsgBox ("The strings DO NOT match")
              
        End If

  
Copy the above and paste it into a file names stringCompare.vbs or download a copy from:


Mark

YouTube Channel: [WATCH, RATE, SUBSCRIBE]

This is an image... the video is at the top!

0 comments: