Skip to main content

PowerShell function to check whether or not the current user is in the local Administrators group.

function Test-Admin {
    $identity  = [System.Security.Principal.WindowsIdentity]::GetCurrent()
    $principal = New-Object System.Security.Principal.WindowsPrincipal($identity)
    return $principal.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)
}

#
# Usage:
if (!(Test-Admin)) {
    $bootstrapperFile = ${function:Get-Boxstarter}.File
    if ($bootstrapperFile) {
        Write-Host "User is not running with administrative rights. Attempting to elevate..."
        $command = "-ExecutionPolicy bypass -noexit -command . '$bootstrapperFile';Get-Boxstarter $($args)"
        Start-Process powershell -verb runas -argumentlist $command
    }
    else {
        Write-Host "User is not running with administrative rights.`nPlease open a PowerShell console as administrator and try again."
    }
    return
}