Private/Assert-Administrator.ps1
|
function Assert-Administrator { <# .SYNOPSIS Validates that the current session is running with Administrator privileges. .DESCRIPTION Checks the current Windows identity for membership in the built-in Administrators role. Throws a terminating UnauthorizedAccessException if the session is not elevated, which allows callers to handle the error gracefully via try/catch. #> [CmdletBinding()] param() process { $identity = [Security.Principal.WindowsIdentity]::GetCurrent() $principal = [Security.Principal.WindowsPrincipal]$identity $adminRole = [Security.Principal.WindowsBuiltInRole]::Administrator if (-not $principal.IsInRole($adminRole)) { throw [System.UnauthorizedAccessException]::new( 'This operation requires elevated Administrator privileges. ' + 'Please run PowerShell as Administrator and try again.' ) } } } |