The Computer Oracle

Detect if PowerShell is running as administrator

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------


Take control of your privacy with Proton's trusted, Swiss-based, secure services. Choose what you need and safeguard your digital life:
Mail: https://go.getproton.me/SH1CU
VPN: https://go.getproton.me/SH1DI
Password Manager: https://go.getproton.me/SH1DJ
Drive: https://go.getproton.me/SH1CT


Music by Eric Matyas
https://www.soundimage.org
Track title: Quirky Dreamscape Looping

--

Chapters
00:00 Detect If Powershell Is Running As Administrator
00:18 Accepted Answer Score 70
01:00 Answer 2 Score 117
01:17 Answer 3 Score 66
01:45 Answer 4 Score 0
02:08 Thank you

--

Full question
https://superuser.com/questions/749243/d...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#powershell

#avk47



ANSWER 1

Score 117


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




ACCEPTED ANSWER

Score 70


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



ANSWER 3

Score 66


In Powershell 4.0 you can use requires at the top of your script:

#Requires -RunAsAdministrator

Outputs:

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




ANSWER 4

Score 0


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.