Use your PowerShell prompt to differentiate between regular and admin sessions

August 30, 2017

I often find myself switching between regular and administrator PowerShell sessions. If you have one of each session open, the only way to tell the difference between them is to look for the word “Administrator” in the title bar. I’m not sure if it’s the poor contrast in the title bar or if I’m slowly going blind, but I found that to be a pain. So I decided to add it to my PowerShell prompt.

To do so, I added a helper function to my profile called Test-IsAdmin. This simply gets the current WindowsPrincipal and checks if they are in the Administrator role. In an administrator session this will return true. In a regular session it returns false. This works because UAC “hides” your membership in the Administrators group unless you choose to run in an elevated mode. Here is the full Test-IsAdmin implementation:

## Helper function to determine if current session is an admin session
function Test-IsAdmin {
return ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
view raw profile.ps1 hosted with ❤ by GitHub

Then you just call that function and modify your prompt output as desired. This simple implementation adds [ADMIN] in yellow before the path.

## Custom Prompt
function prompt() {
if(Test-IsAdmin) {
Write-Host -NoNewline -Fore Yellow "[ADMIN] "
Write-Host -NoNewline $(Get-Location)
Write-Host -NoNewLine '>'
' '
view raw profile.ps1 hosted with ❤ by GitHub

Here’s what this looks like in an admin session. Having the yellow [ADMIN] tag makes it a lot easier to differentiate.

Admin Session Prompt Output

I love the idea of customizing my PowerShell prompt but most of the customizations I’ve seen don’t really seem useful to me, so this is the first one that has stuck. Do you have a useful prompt customization? If so, comment below and let me know about it.

© 2020 Jesse Barocio. Built with Gatsby