Powershell script to check for elevated permissions

When I provide PowerShell scripts to a customer, I sometimes get a complaint that the script isn’t working. When I go to the customer I suddenly realize that they just execute the script, and don’t right-click on the script and select “Run as administrator” and therefor will run with elevated permissions.

Because this has happened a few times now, I started to include a few extra lines of code in my scripts:

$CurrentPrincipal = New-Object Security.Principal.WindowsPrincipal( [Security.Principal.WindowsIdentity]::GetCurrent( ) )
if ( -not ($currentPrincipal.IsInRole( [Security.Principal.WindowsBuiltInRole]::Administrator ) ) )
Write-Error “This script must be executed with elevated permissions!” -ErrorAction Stop

This little bit of code will give the customer a message stating that the script will need to run with elevated permissions Smile

Leave a Reply

Your email address will not be published. Required fields are marked *