PowerShell: Test-IsAdmin

Scriptimus PowerShell Banner

Sometimes I only want a PowerShell function to run only if the user has local admin rights. This can be tested for by looking for the admin token.

Here’s a function I use.

Function Test-IsAdmin {

 $user = [Security.Principal.WindowsIdentity]::GetCurrent();
 (New-Object Security.Principal.WindowsPrincipal $user).IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator) 
 }

I then call the function in my code using this snippet

 If (!(Test-IsAdmin)) {
 Write-Warning "This script needs admin rights to run!!!"
 $HOST.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") | OUT-NULL
 $HOST.UI.RawUI.Flushinputbuffer()
 Break
 }

Result!

testisadmin

Technical info on MSDN here.

Remember, for a script or module you could use the #Requires statement but this wont work in a function.

#Requires -RunAsAdministrator 

Enjoy.

Advertisements

About Andrew Barnes

A Scripting and Deployment Specialist.
This entry was posted in PowerShell and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

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