Previous Section Table of Contents Next Section

Functions

Functions are one of the workhorses of any script. They perform operations of some kind, and return some kind of result back to the main script. For example, VBScript has a built-in function called Date() that simply returns the current date.

There are built-in functions and custom functions that you write. The only difference between them, of course, is that Microsoft wrote the built-in functions and you write your custom ones. The sample login script has a couple of custom functions.


Function GetIP()

 Set myObj = GetObject("winmgmts:" & _

  "{impersonationLevel=impersonate}" & _

  "!//localhost".ExecQuery _

  ("select IPAddress from " & _

  "Win32_NetworkingAdapterConfiguration" & _

  " where IPEnabled=TRUE")



 'Go through the addresses

 For Each IPAddress in myObj

  If IPAddress.IPAddress(0) <> "0.0.0.0" Then

   LocalIP = IPAddress.IPAddress(0)

   Exit For

  End If

 Next

 GetIP = LocalIP

End Function



Function IsMemberOf(sGroupName)

  Set oNetwork = CreateObject("WScript.Network")

  sDomain = oNetwork.UserDomain

  sUser = oNetwork.UserName

  bIsMember = False

  Set oUser = GetObject("WinNT://" & sDomain & "/" & _

   sUser & ",user")

  For Each oGroup In oUser.Groups

    If oGroup.Name = sGroupName Then

      bIsMember = True

      Exit For

    End If

  Next

  IsMemberOf = bIsMember

End Function

You'll notice that these all begin with the declaration Function, followed by the name of the function. They can include a list of input parameters, as the IsMemberOf function does. All of them return some information, too. Notice that the last line of each function sets the function name equal to some other variable; this action returns that other variable's value as the result of the function.

If this is not making sense, don't worry. For now, just make sure you can recognize a function at 30 feet by the keyword Function. I cover functions in more detail in Chapter 5, in the section, "What Are Functions?"

Why use functions? Well, in the case of intrinsic functions, they perform a very valuable service, providing information like the date and time, and allowing you to manipulate data. Custom functions do the same thing. Custom functions, however, can be a lot more useful in the end. Take the IsMemberOf function as an example. That function tells me if the current user is a member of a specific domain user group or not. It took me a couple of hours to figure out how to perform that little trick. In the future, though, I can just paste the function into whatever script I need, and I'll never have to spend those couple of hours again. Bundling the task into a function makes it easily portable between scripts, and allows me to easily reuse my hard work.

    Previous Section Table of Contents Next Section