Marc Lognoul's IT Infrastructure Blog

Cloudy with a Chance of On-Prem

PowerShell: Testing if the Logged On User is Really Admin

PowerShell

Since the introduction of User Account Control (UAC) with Windows Vista/Server 2008, scripter have to deal with detecting if the user executing commands or scripts is effectively granted the necessary privileges, ie. is running with elevated privileges.

While you can find plenty of snippets and functions on the Internet to achieve this goal. The reasons why I use this one hereunder are the following:

  • It is compatible with all (decently recent) Windows versions
  • It works with all languages since no names are used
  • It is fairly fast: the speed directly depends on the user’s token size

Function IsCurrentUserElevated()
{
[bool]$IsElevated = $False
If ([System.Environment]::OSVersion.Version.Major -lt 6)
{$IsElevated = [bool]((whoami /groups /SID) -match “S-1-5-32-544”)}
Else
{$IsElevated = [bool]((whoami /groups) -match “S-1-5-32-544”) -and [bool]((whoami /groups) -match “S-1-16-12288”)}
Return $IsElevated
}

Note:  If someone has a native PowerShell replacement for fetching a user token please let me know ;).

Additional information’s:

Advertisements

Author: Marc Lognoul

Relentless cloud professional. Restless rider. Happy husband. Proud father. Opinions are my own.

Comments are closed.