PowerShell

PowerShell: Changing the Look of the Prompt

PowerShell comes with a standard prompt whose configuration is stored in the prompt function. The good news is that we are able to change this prompt function to suit our needs. In this blog post, I will show you how you can change this prompt and I will give you some examples.

Subject

We are investigating this subject:

And we are also investigating the function which is related to this default prompt:

(Get-Item function:prompt).ScriptBlock

This is the default prompt. For customizing, we need to change this default prompt.

Changing the Look of the Prompt

Here are 4 examples you can use for your prompt or for further customization.

Showing the Date

function prompt {

    "$(Get-Date)> "

}

Default Prompt + Computername

function prompt {

    "PS [$env:COMPUTERNAME]> "

}

If PowerShell is started as administrator, then show [Administrator]

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)) { "[ADMINISTRATOR]: " }
      else { '' }
    ) + 'PS ' + $(Get-Location) +
      $(if ($NestedPromptLevel -ge 1) { '>>' }) + '> '
  }

Showing the Username

function prompt {

  "PS [$env:USERNAME]> "

}

I hope I was able to spark some ideas on how to change the prompt of your PowerShell session.

More about Prompts here: https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_prompts?view=powershell-7.2#:~:text=The%20Prompt%20function%20determines%20the,defining%20your%20own%20Prompt%20function.&text=The%20Prompt%20function%20must%20return,is%20formatted%20as%20a%20string.

If you are wondering how you can permanently implement your custom prompt have a look at my article about PowerShell Profiles: How to create PowerShell Profiles

Categories: PowerShell

Tagged as: ,

3 replies »

  1. Hallo Patrick,
    hast Du eine Idee, wie man mit dem Powershell die BootSequenz des PCs aus dem (nicht-UEFI) BIOS auslesen kann?
    Herzlichen Dank für Deine Hilfe!
    Gruß,
    Yury

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.