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!”
    Break
}

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!

Cheers,

Michael

P.S.: Thanks to Microsoft’s Scripting Guy “Ed Wilson”. Check out his blog: http://blogs.technet.com/b/heyscriptingguy/

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s