Test if PowerShell has been run as Administrator

A quick utility function to add into your scripts to test whether or not PowerShell has been run as Administrator.

The function returns a boolean value ($True or $False).

function Test-IsAdmin 
{
    $CurrentIdentity = [Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()

    $IsAdmin = $CurrentIdentity.IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")

    Write-Output $IsAdmin
}

Example Usage

if (Test-IsAdmin)
{
    <#
        PowerShell is running as administrator.

        Crack on and do other scripty stuff. :)
    #>
}
else
{
    <#
        PowerShell is NOT running as Administrator.

        Throw some useful error or warning, advising the users to
        run PowerShell again, but run as administrator.
    #>
}

Leave a Reply

Your email address will not be published. Required fields are marked *