Issue

An example of using a custom PowerShell prompt to display some simple elements without complicating the Prompt.

Solution

We can use a custom function and load from PowerShell Profile.
We can incorporate the following information into our prompt:

  • The current working directory (but in the shell title).
  • The user context and hostname (again, in the shell title).
  • The Get-History ID (to identify and rerun previous commands).
  • A timestamp for some basic benchmarking and a reminder for when a command was run.
  • A visual representation of whether the shell is elevated or not.
    • In this case, we will change the history indictor from green to yellow, as well as adjust the title.


function Prompt {
    # DEFINE VARIABLES: -------------------------------------------------------
    # Current Security Principal to check for Admin Mode.
    $Identity = [Security.Principal.WindowsIdentity]::GetCurrent()
    $Principal = [Security.Principal.WindowsPrincipal] $Identity

    # Time 24hrs HH:MM:SS
    $TimeStamp = (Get-Date -UFormat %T).ToString()

    # Command History for easy reference.
    $History = @(Get-History)

    # Increment the history count.
    if ($History.Count -gt 0) {
        $LastItem = $History[$History.Count - 1]
        $LastId = $LastItem.Id
    } # END if ($History.Count -gt 0)
    $NextCommand = $LastId + 1

    # BUILD THE PROMPT: -------------------------------------------------------
    $(if (Test-Path Variable:/PSDebugContext) {
            # DEBUG MODE.
            '[DBG]: '
        }
        elseif ($principal.IsInRole([Security.Principal.WindowsBuiltInRole]"Administrator")) {
            # ADMINSTRATOR MODE:
            # Set the Title to Admin and the current location.
            $Host.UI.RawUI.WindowTitle = "[ ADMIN ] : " + $(Get-Location) + " > "

            # Set the prompt with the history as 'Yellow' to reflect Admin Mode with the current time.
            Write-Host -ForegroundColor Yellow -NoNewline " [ $NextCommand ] "
            Write-Host -ForegroundColor White -NoNewline $TimeStamp

        }
        else {
            # NON-ADMINISTRATOR MODE:
            # Set the Title to Non-Admin and the current location.
            $Host.UI.RawUI.WindowTitle = "[ NON-ADMIN ] : " + $(Get-Location) + " > "

            # Set the prompt with the history as 'White' to reflect Non-Admin Mode with the current time.
            Write-Host -ForegroundColor Green -NoNewline " [ $NextCommand ] "
            Write-Host -ForegroundColor White -NoNewline $TimeStamp

        } # END if (Test-Path Variable:/PSDebugContext)

        # Check if nested and add ' > ' indicator.
    ) + $(if ($NestedPromptLevel -ge 1) { '>>' }) + ' > '

} # END function Prompt #######################################################

Result

First, our standard shell.
Custom-PowerShell-Prompt-Standard

And finally, our elevated shell.
Custom-PowerShell-Prompt-Admin

Happy coding!