Better PowerShell Prompts (Part 2)

by Aug 26, 2022

In the previous tip we illustrated how you can define your own “prompt” function to customize the PowerShell prompt.

One useful item could be to indicate in your prompt whether you are currently granted full Administrator privileges. Here is a prompt function that does this, taken from the PowerShell documentation:

function prompt 
{
  $identity = [Security.Principal.WindowsIdentity]::GetCurrent()
  $principal = [Security.Principal.WindowsPrincipal] $identity
  $adminRole = [Security.Principal.WindowsBuiltInRole]::Administrator

  $(if (Test-Path variable:/PSDebugContext) { '[DBG]: ' }
    elseif($principal.IsInRole($adminRole)) { "[ADMIN]: " }
    else { '' }
  ) + 'PS ' + $(Get-Location) +
    $(if ($NestedPromptLevel -ge 1) { '>>' }) + '> '
}

You can also spice up your prompt using colors. On Windows PowerShell, use the Write-Host cmdlet (but always make sure your “prompt” function returns at least one character, or else you get the default prompt):

{
    $dateTime = Get-Date -Format "dd.MM.yyyy HH:mm:ss"
    $currentDirectory = Get-Location
    $UncRoot = $currentDirectory.Drive.DisplayRoot
    $host.Ui.RawUI.WindowTitle = Convert-Path $currentDirectory

    Write-Host "$dateTime" -NoNewline -ForegroundColor White
    Write-Host " $UncRoot" -ForegroundColor Gray
    # Convert-Path needed for pure UNC-locations
    Write-Host "PS[" -NoNewline -ForegroundColor Yellow
    Write-Host $env:username -NoNewline -ForegroundColor Green
    Write-Host "]>" -NoNewline -ForegroundColor Yellow
    # output at least one character:
    return " "
}


Twitter This Tip! ReTweet this Tip!