Check if the user is a local administrator on the external machine

I am writing an application that aggregates all the event log entries on each of several different servers. I can get the event logs by going to MachineName

before EventLog.GetEventLogs

. This can usually be unfortunate at the point that the user is not a local administrator on that computer, so I would like to test it ahead of time and move on to the next set of servers if so.

For Each svr As String In Servers

    'TODO: check to see if they are a local administrator, else continue for

    Dim logs As List(Of EventLog) = EventLog.GetEventLogs(svr).ToList
    For Each log As EventLog In logs


In most solutions like here , only check if the user is an administrator on the current executable machine.

Dim user As WindowsIdentity = WindowsIdentity.GetCurrent()
Dim principal As New WindowsPrincipal(user)
Dim isAdmin As Boolean = principal.IsInRole(WindowsBuiltInRole.Administrator)



source to share

1 answer

I'll share a partial solution, but I'm not entirely happy with it, so if anyone has anything better I would gladly accept their answer.

The following function will return or the user does not belong to a specific user group (in my case "Administrators"

) on any computer.

Imports System.DirectoryServices.AccountManagement

Public Shared Function IsMemberOfGroup(userName As String, machineName As String, memberGroup as String) As Boolean
    Dim isMember As Boolean = False
    Using rootContext As New PrincipalContext(ContextType.Machine, machineName), _
          grp As GroupPrincipal = GroupPrincipal.FindByIdentity(rootContext, memberGroup), _
          usr As UserPrincipal = UserPrincipal.FindByIdentity(rootContext, IdentityType.SamAccountName, userName)
        If grp IsNot Nothing AndAlso usr IsNot Nothing Then
            ' Check if the user is a member of the group.
            isMember = grp.GetMembers(True).Contains(usr)
            isMember = False
        End If
    End Using
    Return isMember
End Function


Kavita is that the user executing this method must be an administrator to have the rights to this information set in PrincipalContext

. I was hoping that the application would be able to determine if the user running the application is an administrator.

The only way to make it super useful is to call it up and see if it shows "Access Denied ", similar to hometoast , but it still doesn't seem super "clean"



All Articles