techthoughts2
12/3/2017 - 3:44 AM

Test-RunningAsAdmin

Evaluates if current PowerShell session is running under the context of an Administrator

<#
.Synopsis
   Tests if PowerShell Session is running as Admin
.DESCRIPTION
   Evaluates if current PowerShell session is running under the context of an Administrator
.EXAMPLE
    Test-RunningAsAdmin

    This will verify if the current PowerShell session is running under the context of an Administrator
.EXAMPLE
    Test-RunningAsAdmin -Verbose

    This will verify if the current PowerShell session is running under the context of an Administrator with verbose output
.OUTPUTS
   System.Boolean
.NOTES
   Author: Jake Morrison - @jakemorrison - http://techthoughts.info
#>
function Test-RunningAsAdmin {
    [CmdletBinding()]
    Param()
    $result = $false #assume the worst
    try {
        Write-Verbose -Message "Testing if current PS session is running as admin..."
        $eval = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
        if ($eval -eq $true) {
            Write-Verbose -Message "PS Session is running as Administrator."
            $result = $true
        }
        else {
            Write-Verbose -Message "PS Session is NOT running as Administrator"
        }
    }#try
    catch {
        Write-Warning -Message "Error encountering evaluating runas status of PS session"
        Write-Error $_
    }#catch
    return $result
}