Shorten the path in your PowerShell prompt

Anyone who has used PowerShell is familiar with how it shows the current working directory in the prompt as below:

PS C:\Documents and Settings\Mike\PowerShell\Scripts>

This is all well and good until you’re knee deep in directories (or registry keys, or the structure of any another provider) and the prompt is taking up more than half of the current line. Naturally PoSH wraps, but this can make it hard to read what you’ve typed or cut and pasted.

Since the prompt is actually defined by a function named ‘prompt’, a quick and dirty way to shorten the prompt is to type:

function prompt {”>”}

But I usually still want to know where I am.  You can modify your $profile to include a ‘prompt’ function that overrides the default, and do it in such a way that long path descriptions are a thing of the past. Just add the following to your $profile and your long prompts will appear similar to the following:

PS C:\Documents and Settings\…\Scripts>

###
# TruncatePath
# Version 1.1 (14 Apr 2009)
# Description: Replaces long provider paths in the prompt with ellipses
# Notes: Place in your profile
#
# By Mike Hays, <a href="http://www.mike-hays.net">http://www.mike-hays.net</a>
###
 
$MaxPathLength = 32
$ShowFullPath = $False
 
$prompt = New-Object System.Object
$prompt  | Add-Member -type NoteProperty -name MaxPathLength -value $MaxPathlength
$prompt  | Add-Member -type NoteProperty -name ShowFullPath -value $ShowFullPath
 
Function Prompt
{
	$currentPath = (Get-Location).Path
 
	if ( ($currentPath.Length -gt $prompt.MaxPathlength) -and ($prompt.ShowFullPath -ne $true) `
		-and (($currentPath.Split("\")).Count -gt 3) )
	{
		$currentPathSplit = $currentPath.Split("\")
		$truncatedPath = $currentPathSplit[0] + "\" + $currentPathSplit[1] + "\" `
			+ "..." + "\" + $currentPathSplit[$currentPathSplit.Length - 1]
 
		if ($truncatedPath.Length -lt $currentPath.Length)
		{
			$displayPath = $truncatedPath
		}
		else
		{
			$displayPath = get-location
		}
	}
	else
	{
		$displayPath = get-location
	}
 
	Write-Host ("PS ") -NoNewLine -ForegroundColor DarkYellow ; Write-Host ("" + `
	$displayPath + "&gt;") -NoNewLine
	return " "
}

You can get the full path if you need it by typing “Get-Location” or its default alias “pwd” (a unixism for print working directory), or you can disable path truncation by typing:

$prompt.ShowFullPath = $true

Happy PoSHing!

Mike

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">