Test admin rights within PowerShell script?

resolver101 picture resolver101 · Apr 3, 2012 · Viewed 17.3k times · Source

Whats the best/easiest way to test for administrative rights in a PowerShell script?

I need to write a script that requires administrative rights and want to know the best way to achieve it.

Answer

Andy Arismendi picture Andy Arismendi · Apr 3, 2012

This is the little function I have in a security module:

function Test-IsAdmin {
    try {
        $identity = [Security.Principal.WindowsIdentity]::GetCurrent()
        $principal = New-Object Security.Principal.WindowsPrincipal -ArgumentList $identity
        return $principal.IsInRole( [Security.Principal.WindowsBuiltInRole]::Administrator )
    } catch {
        throw "Failed to determine if the current user has elevated privileges. The error was: '{0}'." -f $_
    }

    <#
        .SYNOPSIS
            Checks if the current Powershell instance is running with elevated privileges or not.
        .EXAMPLE
            PS C:\> Test-IsAdmin
        .OUTPUTS
            System.Boolean
                True if the current Powershell is elevated, false if not.
    #>
}