How Can I Determine if a User is a Local Administrator?

How Can I Determine if a User is a Local Administrator?

  • Comments 4
  • Likes
Hey, Scripting Guy! Question

Hey, Scripting Guy! Some of the things we do in our logon scripts require the user to be a local administrator. How can the script tell if the user is a local admin or not?

-- GM, Denver, CO

SpacerHey, Scripting Guy! AnswerScript Center

Hey, GM. The best way to do that is to check the membership of the local Administrator’s group and see if the user is in there. To do that, you need to first determine the name of the computer that the script is running on. That’s required so you can use ADSI and the WinNT provider to “bind” to the local Administrators group and retrieve the list of group members.

After that, you must then determine the logon name of the logged-on user. As soon as you know that, you can loop through the Administrators group and see if the logged-on user is a member.

Listen, don’t panic; all that takes only a few lines of code:

Set objNetwork = CreateObject("Wscript.Network")
strComputer = objNetwork.ComputerName
strUser = objNetwork.UserName

Set objGroup = GetObject("WinNT://" & strComputer & "/Administrators")
For Each objUser in objGroup.Members
    If objUser.Name = strUser Then
        Wscript.Echo strUser & " is a local administrator."
    End If
Next

So what’s happening in this script? Well, first we create an instance of the Wscript Network object; using that object, we can figure out the names of both the computer and the logged on user.

With those names firmly in hand, we then use the WinNT provider to bind to the Administrators group on the computer in question. After binding to the group we set up a For Each loop to walk through the group membership (the Members property is stored as an array, which is why we need to use For Each). For each member found, we check to see whether the member’s logon name (objUser.Name) is equal to the name of the logged-on user (a value we stored in the variable strUser).

And what if the member name and the logged-user name match? Well, that means that the logged-on user must be a local administrator; otherwise he or she wouldn’t be a member of the Administrators group. In this sample script, we merely echo the fact that the user is a local administrator; in your actual logon script, you could go ahead and carry out any tasks that require admin privileges.

For more information about using the WinNT provider, see the ADSI SDK on MSDN.

Your comment has been posted.   Close
Thank you, your comment requires moderation so it may take a while to appear.   Close
Leave a Comment
  • Good One!!!

  • safadsf

  • This works fine if the user is actually directly a member of the local Administrators security group. It will not work if they are a member of a domain security group such as the Domain Admins group. Basically, this doesn't work for nested group membership.

  • good tip