Detect elevated privileges

Sometimes you get a requirement to start a Powershell script from an elevated prompt. Here is a quick function to check that :

 

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

This will return a simple boolean so you can use it this way :

 

If(Test-ElevatedPrompt){
  Write-host "Elevated Privileges : OK"
}
Else{
  Write-Error "This script required an elevated privilege, please check"
}

Then, you could also enforce the script to create a new process “as Administrator” using the following lines :

# Create a new process object that starts PowerShell
$newProcess = new-object System.Diagnostics.ProcessStartInfo "PowerShell";
# Specify the current script path and name as a parameter
$newProcess.Arguments = $myInvocation.MyCommand.Definition;
# Indicate that the process should be elevated
$newProcess.Verb = "runas";
# Start the new process
[System.Diagnostics.Process]::Start($newProcess);
# Exit from the current
exit

Of course ! An UAC Prompt will appear to accept/decline that elevated shell !

 

 

Enjoy !

 

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

How to whitelist website on AdBlocker?

How to whitelist website on AdBlocker?

  1. 1 Click on the AdBlock Plus icon on the top right corner of your browser
  2. 2 Click on "Enabled on this site" from the AdBlock Plus option
  3. 3 Refresh the page and start browsing the site