Thursday, April 30, 2020

Check For Admin Rights with PowerShell

Recently I was trying to determine if a domain user is a local Administrator of their workstation and found many options... Note that there is a difference in checking if the user is a local Administrator and checking if the command is running in an elevated context. Here's what worked best for me...

Check if user is in local Administrators group:
$userIsAdmin = [bool](Get-LocalGroupMember Administrators | Where-Object name -Like "*$env:USERNAME")
This method seemed to fail on some workstations with domain trust issues. If the user showed up as it's SID in the local administrators group, the -like wouldn't match and thus this method wasn't consistent.

Instead of checking the local Administrators group for list of users, leveraging the com "whoami" appears to evaluate correctly in all testing.
$userIsAdmin = [bool](whoami /groups /fo csv | ConvertFrom-Csv | Where-Object SID -eq "S-1-5-32-544")

Check if running as Administrator:

If you're looking to check if your script is running as Administrator (aka, in an elevated context), I found these two options.
$runningAsAdmin = [bool]([Security.Principal.WindowsIdentity]::GetCurrent().Groups | Select-String 'S-1-5-32-544')
I'm preferring the below option even though it's a little bit longer.
$runningAsAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")

Happy Scripting!

No comments:

Post a Comment