Search code examples
powershelladministratorelevation

How to determine if user has admin rights, but script not running elevated


I have tried various solutions online (some not very clear on whether they are for detecting script being elevated, as opposed to script running under a user that doesn't need to supply creds to UAC to elevate). Like the below. They show false when running under a domain admin account, not elevated. Likewise (obviously) a domain account without any admin rights. They both show true when running elevated though.

PS C:\Users\xxxxxxxxx.adm> (new-object security.principal.windowsprincipal([security.principal.windowsidentity]::getcurrent())).isinrole([security.principal.windowsbuiltinrole]::administrator)


PS C:\Users\xxxxxxxxx.adm> (([security.principal.windowsidentity]::getcurrent().groups).value -contains 'S-1-5-32-544')

How can I achieve the check needed?

Note: In my environment, helpdesk admin privileges are provided by a double nested group, not domain admins, added to the adminstrator group on the workstations.


Solution

  • You can adapt the solution from this answer to a conceptually related question (the linked solution allows you to perform the same test for any given user, not just the current one):

    # Load the required assembly (a no-op if already loaded).
    # NOTE: No longer needed in PowerShell 7, where this assembly is preloaded.
    Add-Type -AssemblyName System.DirectoryServices.AccountManagement
    
    # 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,
    # either directly or indirectly.
    [DirectoryServices.AccountManagement.UserPrincipal]::Current.
      GetAuthorizationGroups().SID.Value -contains 'S-1-5-32-544'
    

    In essence, this tells you whether the current user account is an administrator on the local machine in principle and whether it can therefore run as itself when elevation is requested.