
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 !