Check if PowerShell is running as administrator

You can tell if PowerShell is running with administrator privileges (a.k.a “elevated” rights) with the following snippet:

[Security.Principal.WindowsIdentity]::GetCurrent().Groups -contains 'S-1-5-32-544'

Breaking apart what this does:

  • [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.
  • -contains "S-1-5-32-544" returns true if groups contains the Well Known SID of the Administrators group (the identity will only contain it if “run as administrator” was used) and otherwise false.

Bonus

In Powershell >= 4.0 you can use requires statement at the top of your script to prevent a script from running as regular user:

#Requires -RunAsAdministrator

If the script is invoked from a non-elevated PowerShell process you’ll receive the following error:

The script 'run_as_admin.ps1' cannot be run because it contains a "#requires" statement for running as Administrator. The current Windows PowerShell session is not running as Administrator. Start Windows PowerShell by using the Run as Administrator option, and then try running the script again.
At line:1 char:1
+ C:\demo\run_as_admin.ps1
+ ~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : PermissionDenied: (run_as_admin.ps1:String) [], ScriptRequiresException
+ FullyQualifiedErrorId : ScriptRequiresElevation

To run a specific command from an elevated window

Start-Process -FilePath powershell.exe -ArgumentList {$ScriptBlock} -Verb RunAs
Start-Process -FilePath pwsh.exe -ArgumentList {$ScriptBlock} -Verb RunAs

For example:

Start-Process -FilePath powershell.exe -ArgumentList {
    SFC /scannow
} -Verb RunAs

To run a specific script from an elevated window:

Start-Process powershell.exe -ArgumentList '-noprofile -file MyScript.ps1' -Verb RunAs

To run an entire PowerShell session prompting for UAC:

Start-Process powershell.exe -Verb runAs

To run a process with elevated rights under a different user:

# variables
$mmc = "$($env:SystemDrive)\Windows\System32\mmc.exe"
$msc = "$($env:SystemDrive)\Windows\System32\compmgmt.msc"

# credentials
$username   = "DOMAIN\USERNAME"
$securePass = ConvertTo-SecureString "PASSWORD" -AsPlainText Force
$cred       = New-Object System.Management.Automation.PSCredential $username, $securePass

# call MSC
Start-Process powershell.exe -Credential $cred -ArgumentList "Start-Process -FilePath $mmc -ArgumentList $msc -Verb runAs"