Nilpo`s Scripting Secrets, Vol I - Determine if a user is an Administrator
(Page 2 of 4 )
I have seen this one asked hundreds of times across various forums and newsgroups. “Is there a way to determine if a user is an Administrator?” Quite often this question goes unanswered, but it doesn’t have to.
Function IsAdminUser(strUserName)
strUserName = Chr(34) & strUserName & Chr(34)
strComputer = "."
Set objWMIService = GetObject("winmgmts:" & strComputer & "rootcimv2")
Set colInstances = objWMIService.ExecQuery("Select * From Win32_GroupUser")
You begin by building a function that queries the Win32_GroupUser class. This class returns several instances that represent the installed users and their group assignments. Each instance will have a GroupComponent that represents the user group and a PartComponent that represents the user name. There will be one instance for every group that a user is in, so there can be several times as many instances as there are users.
blnIsAdmin = False
For Each objInstance In colInstances
arrGroup = Split(objInstance.GroupComponent, ",")
arrAccount = Split(objInstance.PartComponent, ",")
strGroup = Right(arrGroup(1), Len(arrGroup(1)) - InStr(arrGroup(1), "="))
strAccount = Right(arrAccount(1), Len(arrAccount(1)) - InStr(arrAccount(1), "="))
If strGroup = """Administrators""" And strAccount = strUserName Then blnIsAdmin = True
Next
Since this query will return several instances, we’ll use a Boolean value to track the data we’re looking for. It should begin with a default value of false. Next, we loop through each instance, determining the user name and group assignment. If a particular instance finds the user we’re looking for listed with an administrator user group, then the Boolean value is set to true.
IsAdminUser = blnIsAdmin
End Function
The function then returns that Boolean value. So the function can be used like this:
Set WshNetwork = CreateObject("WScript.Network")
strUserName = WshNetwork.UserName
If IsAdminUser(strUserName) Then
WScript.Echo strUserName, "is an administrator."
Else
WScript.Echo strUserName, "is not an administrator."
End If
Next: Wait for a program to end >>
More Windows Scripting Articles
More By Nilpo