Functions/Validations/Test-ElevatedRights.ps1

<#
    .SYNOPSIS
    Tests if the PowerShell session is started as administrator.
    .DESCRIPTION
    Returns $true if the session has elevated rights and $false when not.
    .EXAMPLE
    Test-ElevatedRights
    .EXAMPLE
    # Returns either $true or $false but supresses the warning when the session is not elevated.
    Test-ElevatedRights -WarningAction SilentlyContinue
    .EXAMPLE
    # Log a warning when the session is not elevated as admin but ignore the $false output.
    Test-ElevatedRights | Out-Null
    .EXAMPLE
    Test-ElevatedRights -Verbose | Out-Null
#>


function Test-ElevatedRights {
    [CmdletBinding()]
    [OutputType([bool])]
    [Alias('Confirm-PowershellSessionHasAdministratorRole')]
    param()

    $WindowsIdentity = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent())
    $elevated = ($WindowsIdentity.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator))
    
    if (-not $elevated) {
        Write-Warning 'You need administrative privileges to execute this task. Start the script in a Powershell session launched as administrator.'
        return $false
    }
    
    Write-Verbose 'PowerShell session is elevated to administrative privileges.'
    return $true
}

Export-ModuleMember -Function Test-ElevatedRights -Alias Confirm-PowershellSessionHasAdministratorRole