Exploring Privileges

by Jan 16, 2009

On Vista with UAC enabled, you are not Admin by default. It might be interesting to find out if PowerShell currently has Admin privileges enabled. The following function tells you exactly that:

function isAdmin {
$identity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$principal = new-object System.Security.Principal.WindowsPrincipal($identity)
$admin = [System.Security.Principal.WindowsBuiltInRole]::Administrator
$principal.IsInRole($admin)
}

Simply call the function:

isAdmin

It will return either true or false, depending on your current privileges. You could use that to change the background color of your console based on enabled privileges. To do that, add the function to your profile script. First, open your profile script in Notepad:

Next, add the function at the top of the script. Then, add this:

If (isAdmin) { $host.UI.RawUI.BackgroundColor = 'DarkRed'Clear-Host }

It might also be a good idea to store the privilege status in a variable since your privilege will not change throughout a PowerShell session. Then, you can refer to it later without having to call the .NET code all the time. Add this line to your Profile script:

$isAdmin = isAdmin

Note that some PowerShell extensions, such as PSCX (PowerShell Community Extensions), already define $isAdmin for you.