≡ Menu

PowerShell: Detect if PowerShell script is launched from elevated prompt

Sometimes you get a requirement to start the PowerShell script from an elevated prompt and you don’t want to continue executing the script if the PowerShell window is not in elevated mode. You can easily recognize a PowerShell window is in elevated mode or not just by looking at the title of the Window. You will notice Administrator: prefixed with shell title when it is launched in elevated mode. See below screen for example.

pselevation1

But how to verify this in programmatic way so that we can incorporate the logic within the script to continue only if the shell is in elevated mode?

One approach is, we can verify the WindowTitle of the Shell prompt and check if it has the string Administrator: in it. Below is small piece of code that can help you check the window title.

$h = Get-Host            
$h.UI.RawUI

pselevation2

But problem with it this approach is, the window title is just a string and can be easily overwritten. When someone makes their custom window title, you might ending up thinking that PS window as normal though it is actually elevated prompt.

So, we need much better solution here using which we can detect the elevation of the Shell. Below is a small PowerShell function which returns true or false based on the elevation status of the shell from where you are running it. This function can be easily added to your PowerShell scripts and can be called when you want to verify the elevation status.

            
function Test-IsElevated {            
[CmdletBinding()]            
param(            
)            
 [Security.Principal.WindowsPrincipal] $Identity = [Security.Principal.WindowsIdentity]::GetCurrent()            
 $Identity.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)            
}            

Below is a test script which uses this function and verifies if the script is launched from elevated shell or not.

Code: Test-Elevation.ps1.

[CmdletBinding()]            
Param(            
)            
            
function Test-IsElevated {            
[CmdletBinding()]            
param(            
)            
 [Security.Principal.WindowsPrincipal] $Identity = [Security.Principal.WindowsIdentity]::GetCurrent()            
 $Identity.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)            
}            
            
Write-Host "This script tests if current PowerShell session is in elevated mode or not"            
            
if(Test-IsElevated) {            
 Write-Host "Current PowerShell session is in elevated mode"            
} else {            
 Write-Host "Current PowerShell session is NOT in elevated mode"            
}

Hope you will find this useful.

{ 0 comments… add one }

Leave a Comment