Detect if PowerShell is running as administrator
Sophia Terry
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.
15 Answers
[bool](([System.Security.Principal.WindowsIdentity]::GetCurrent()).groups -match "S-1-5-32-544")Breaking apart what this does:
[bool]- Cast the end result to abool.[System.Security.Principal.WindowsIdentity]::GetCurrent()- Retrieves theWindowsIdentityfor the currently running user.(...).groups- Access thegroupsproperty of the identity to find out what user groups the identity is a member of.-match "S-1-5-32-544"checks to see ifgroupscontains the Well Known SID of the Administrators group, the identity will only contain it if "run as administrator" was used.
([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).
In Powershell 4.0 you can use requires at the top of your script:
#Requires -RunAsAdministratorOutputs:
6The script 'MyScript.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.
Your code :
invoke-command -computername cavl-ghwwsc3 -command { ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()
).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)}is working fine but how to launch it remotely in current user session (not in powershell elevate admin rights because it return my admin isadmin value to remote computer, not current log user if this user isadmin.
one more way:
${env:=::} -eq $nullthe environment variable =:: is presented only you are NOT running the program as administrator.
This should very fast check as it is only variable value comparison. Also it's not so easy to set variable with a name starting with an = due to the syntax rules ,so this is also reliable.