Some PowerShell cmdlets require you to have administrative permissions to run them. If you’re creating a script and you’re using such a cmdlet (e.g. writing a file to the root), it would be nice to check up front if the user who is running the script has the required permissions. After all, what good is it to run the script anyway and throw an error?

Fortunately, there’s an easy way in PowerShell to do this. Add the following code to your script and that’s it. It’s a simple if-statement that will stop the script if you don’t have the required permissions. If you do have administrative permissions, nothing happens and the script will continue processing.

If (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] “Administrator”))
    Write-Warning “You do not have sufficient permissions to run this script!`nPlease re-run this script as an Administrator!”

What happens is that we’re querying the current identity (user who is running the script) and then check whether or not the identity is part of the Built-in Role “Administrator”.

Have fun!



P.S.: Thanks to Microsoft’s Scripting Guy “Ed Wilson”. Check out his blog: