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.

Unknown's avatar

About Andrew Barnes

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

Leave a comment