.Net Classes within VBScript: Doing Randomness and Arrays the Easy Way

.Net and VBScript can play together
Back in 2007, the Microsoft Scripting Guys posted a article titled “Hey, Scripting Guy! Be Careful What You Say.” This article changed everything in the way I scripted because it should how simply you can access some .Net classes through COM callable wrappers. The two they focus on are “System.Random” and “System.Collections.ArrayList”.

Set objRandom = CreateObject("System.Random")
Set objArrList = CreateObject("System.Collections.ArrayList")

ArrayList

When scripting in AD, Exchange or even the desktop, I am consistently working with arrays. Adding items and sorting arrays always required custom functions, overly wordy statements or re-dimensioning. This made working with arrays cumbersome. Their example for sorting the non-.net way:

For i = (UBound(arrNames) - 1) to 0 Step -1
    For j= 0 to i
        If UCase(arrNames(j)) > 
          UCase(arrNames(j+1)) Then
            strHolder = arrNames(j+1)
            arrNames(j+1) = arrNames(j)
            arrNames(j) = strHolder
        End If
    Next
Next

Now, using System.Collections.ArrayList:

DataList.Sort()

You can find a complete list of available methods here: ArrayList Class.

Random

Random numbers are handy for several uses. I typically use them for part of a file name when outputting temp files. Another great use is for auto-generating computer names in a test lab or deployment scenario.

In VB though, this was cumbersome and I always had to look up the exact syntax. And, the syntax isn’t exactly intuitive.

Randomize
Wscript.Echo Int((100 - 1 + 1) * Rnd + 1)

With the System.Random class, this is a lot easier:

Set objRandom = CreateObject("System.Random")
Wscript.Echo objRandom.Next_2(1000000,9999999)

You can find a complete list of available methods here: Random Class.