Testing for Admin Privileges in PowerShell

Sometimes when running a PowerShell script you may need to test at the beginning whether the process it was called from had Windows admin privileges in order to be able to achieve what it needs to do. Prior to PowerShell v4 I had used something along the lines of the following to test for this condition - not the most obvious piece of code ever to be fair:


function Test-IsAdmin {

(\[Security.Principal.WindowsPrincipal\] \[Security.Principal.WindowsIdentity\]::GetCurrent()).IsInRole(\[Security.Principal.WindowsBuiltInRole\] "Administrator")

}

Thanks to Jeff Hicks, I saw a tip of his for a new way to achieve this in PowerShell v4.

http://mcpmag.com/articles/2013/12/10/favorite-powershell-4-features.aspx

All you need to do is place the following at the top of your script and PowerShell will test for the condition before running anything else in the script.


#requires -version 4.0 #requires –runasadministrator

Let’s look at a couple of examples to illustrate this. In the first example we will run the following two scripts as a user who does not have admin privileges and compare the results.

Test-AdminPriv.ps1


function Test-IsAdmin {

(\[Security.Principal.WindowsPrincipal\] \[Security.Principal.WindowsIdentity\]::GetCurrent()).IsInRole(\[Security.Principal.WindowsBuiltInRole\] "Administrator")

}

if (!(Test-IsAdmin)){

throw "Please run this script with admin priviliges"

} else {

Write-Host "Got admin" }

Test-RunAsAdministrator.ps1


#requires -version 4.0 #requires –runasadministrator

Write-Host "Got admin"

If we now elevate the PowerShell session to have admin privileges then we no longer have the issue.