Detect if PowerShell is running as administrator

powershell

How can I tell in my scripts if PowerShell is running with administrator privileges?

I need to know because I'm trying to run a program that requires the ability to open protected ports.

Best Answer

[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.