Script Sample - Checking if the Prompt for current script is Elevated or not

@20aman    Nov 19, 2018

Multiple times I have run into scenarios where the end users were reporting issues with the script but eventually, it turned out to be an access issue. The script required to be executed from an Elevated console (i.e. Run As Administrator) but the end user was trying to execute it as a normal user. Wouldn't it be nice if the script can check itself if it is being executed from an Elevated prompt or not and would report the same as a requirement.

This script sample can be reused in multiple scenarios and in multiple scripts. It will ensure that the script is executed only via an elevated prompt or else it will throw error with relevant details for the end user to take corrective action.

Script workings

The script first fetches the current Windows security principal by using the below commands:

$WindowsID = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$WindowsPrincipal = New-Object System.Security.Principal.WindowsPrincipal($WindowsID)

It then fetches the Administrator Role related details using below commands:

$adminRole = [System.Security.Principal.WindowsBuiltInRole]::Administrator

Now that it have both the required information, the script checks if the current Windows Principal is part of the Administrator role or not by using below condition:

if ($WindowsPrincipal.IsInRole($adminRole))
{
    return $True
}
else
{
    return $False
}

The complete script sample turns this into a reusable logic and provides a template for using this with other code.

Location of the Script

You can find this script in GitHub at this location: Get-IsElevated.ps1





Comments powered by Disqus