Detect if PowerShell is running as administrator

Solution 1:

[bool](([System.Security.Principal.WindowsIdentity]::GetCurrent()).groups -match "S-1-5-32-544")

Breaking apart what this does:

  • [bool] - Cast the end result to a bool.
  • [System.Security.Principal.WindowsIdentity]::GetCurrent() - Retrieves the WindowsIdentity for the currently running user.
  • (...).groups - Access the groups property of the identity to find out what user groups the identity is a member of.
  • -match "S-1-5-32-544" checks to see if groups contains the Well Known SID of the Administrators group, the identity will only contain it if "run as administrator" was used.

Solution 2:

([Security.Principal.WindowsPrincipal] `
  [Security.Principal.WindowsIdentity]::GetCurrent() `
).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)

This retrieves the current Windows identity and returns $true if the current identity has the Administrator role (i.e., is running elevated).