Customising the PowerShell prompt

by Ed Fisher on 2009-07-30

in Whatever

psicon Today a student asked me how to customise the PowerShell prompt, such that the running count of commands, as well as the last command, would appear in the prompt. He had some ideas from other posts but they weren’t quite there, so I started digging around and this is what I came up with.

  • function prompt
  • {
  • ## Initialize vars
  • $depth_string = ""
  • ## Get the Stack -Pushd count
  • $depth = (get-location -Stack).count
  • ## Create a string that has $depth plus signs
  • $depth_string = "+" * $depth
  • ## Get the history. Since the history may be either empty,
  • ## a single item or an array, the @() syntax ensures
  • ## that PowerShell treats it as an array
  • $history = @(get-history)
  • ## If there are any items in the history, find out the
  • ## Id of the final one.
  • ## PowerShell defaults the $lastId variable to ’0′ if this
  • ## code doesn’t execute.
  • if($history.Count -gt 0)
  • {
  • $lastItem = $history[$history.Count - 1]
  • $lastId = $lastItem.Id
  • }
  • ## The command that we’re currently entering on the prompt
  • ## will be next in the history. Because of that, we’ll
  • ## take the last history Id and add one to it.
  • $nextCommand = $lastId + 1
  • ## Get the current location
  • $currentDirectory = get-location
  • ## Get the last command
  • $lastcommand = get-history -count 1|select -exp commandline
  • ## Set the Windows Title to the current location
  • $host.ui.RawUI.WindowTitle = "PS: " + $lastcommand
  • ## And create a prompt that shows the command number,
  • ## and current location
  • "command #$nextCommand $currentDirectory `n$($depth_string)PS>"
  • }

Copy the above (without the callouts of course) into your profile and you should be good to go. Thanks to JJarava and EBGreen for information they posted at
http://stackoverflow.com/questions/157923/customizing-powershell-prompt-equivalent-to-cmds-mpg
and to Marco Shaw for answering a question posted at
http://www.vistax64.com/powershell/240095-prompt-function-last-command-entered.html

Hope you can make some use of it.

You might also enjoy:

  1. howto://change UPN suffixes with PowerShell
  2. howto://create user mailboxes with powershell
  3. Enumerating services with PowerShell
  4. Scripting AD group creation using dsadd

{ 1 comment… read it below or add one }

Anonymous 2009-07-31 at 13:00

First thank you for the example and the research. From what you provided I was able to finally get a working function.
—–>code start
function prompt
{
$host.us.rawui.windowtitle = "PS $pwd"
"[$((get-history -count 1).ID +1)]PS>"
}

—–>Code end

Reply

Leave a Comment

Previous post:

Next post: