Is there a way to check an arbitrary security principal for Administrative rights on a local serverwith PowerShell?

Viewed 350

Many examples on the web show the way to check current user for Administrative privileges using

[Security.Principal.WindowsPrincipal]    
[Security.Principal.WindowsIdentity]::GetCurrent()

Is there a similar way to check not the 'current' identity, but any (local or domain, for example, retrieved from Get-ACL cmdlet) when running commands on a particular server.

I checked https://docs.microsoft.com/en-us/dotnet/api/system.security.principal.windowsidentity.-ctor?view=netframework-4.7.2#System_Security_Principal_WindowsIdentity__ctor_System_String_, but couldn't find a way to do it (only if you use constructor with UPN parameter, which is not suitable in my case). I would appreciate any hint.

1 Answers

You can try the following function, which, for a given user name:

  • tries to find the underlying identity (NT user account) in the same context as the calling user (domain vs. local); the user name may be specified in several formats, among them the NTLM format (<domain>\<username>).
  • then tests that identity for (static) membership in the built-in local Administrators group.
function Test-LocalAdminGroupMembership {
  param([string] $user)

  # Load the required assembly (a no-op if already loaded).
  Add-Type -AssemblyName System.DirectoryServices.AccountManagement

  # Obtain the specified user as a UserPrincipal instance.
  $up = try {
    if (-not $user) { # default to current user
      [System.DirectoryServices.AccountManagement.UserPrincipal]::Current
    } else {
      [System.DirectoryServices.AccountManagement.UserPrincipal]::FindByIdentity(
        [System.DirectoryServices.AccountManagement.UserPrincipal]::Current.Context,
        $user
      )
    }
  } catch {
    Throw
  }

  # See if the well-known SID of the local Administrators group
  # is among the SIDs of the groups that the user is a member of (PSv3+ syntax).
  $up.GetGroups().SID.Value -contains 'S-1-5-32-544'

}
Related