Skip to content

Instantly share code, notes, and snippets.

@MyITGuy
Last active April 8, 2024 18:28
Show Gist options
  • Save MyITGuy/9761925 to your computer and use it in GitHub Desktop.
Save MyITGuy/9761925 to your computer and use it in GitHub Desktop.
Check if user has Administrator role
function Test-AdministratorContext {
[CmdletBinding()]param()
$CurrentWindowsIdentity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$CurrentWindowsPrincipal = New-Object System.Security.Principal.WindowsPrincipal($CurrentWindowsIdentity)
$IsAdministratorContext = $CurrentWindowsPrincipal.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)
Write-Verbose "Current Context Is Administrator = $IsAdministratorContext"
return $IsAdministratorContext
}
#Check for Admin rights
if (-not ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
Write-Warning "$($MyInvocation.MyCommand) cannot be run because the current Windows PowerShell session is not running as an administrator. Start Windows PowerShell as an administrator and then try running the function again."
exit
}
# Adminsitrator role check
function IsLocalAdministrator() {
$CurrentWindowsIdentity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$CurrentWindowsPrincipal = New-Object System.Security.Principal.WindowsPrincipal($CurrentWindowsIdentity)
$IsInWindowsBuiltInAdministratorRole = $CurrentWindowsPrincipal.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)
return $IsInWindowsBuiltInAdministratorRole
}
# One-liner
(New-Object System.Security.Principal.WindowsPrincipal([System.Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)
function Test-SystemContext {
[CmdletBinding()]param()
$CurrentWindowsIdentity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$IsSystemContext = $CurrentWindowsIdentity.User.Value -eq 'S-1-5-18'
Write-Verbose "Current Context Is SYSTEM = $IsSystemContext"
return $IsSystemContext
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment