Detecting the Administrative Context in PowerShell

By | 2015-09-12

I was writing a PowerShell script and it needed to know whether or not it was running in the administrative context. It’s a bit fiddly but here’s a short bit of PowerShell that sets a boolean variable for it:

$currentIdentity = New-Object System.Security.Principal.WindowsPrincipal([System.Security.Principal.WindowsIdentity]::GetCurrent())
$adminContext = $currentIdentity.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)

Run that and $adminContext will be True if the script is runningĀ asĀ admin, and False if not.