Chasing DevOps

A blog about software development, DevOps, and delivering value.

Use your PowerShell prompt to differentiate between regular and admin sessions

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

Jesse Barocio

Software developer, DevOps engineer, and productivity tool nut. Continuously improving. Have a question or problem you need solved? Email me!

Categories

Instagram