ConvertTo-ShortenedPath

If you have ever customized your PowerShell prompt you have probably had a need (or wish) for a function to “intelligently” shortening the current path. I have written a bunch of functions for this and decided to expand on my earlier versions and release it to the PowerShell Gallery.

First you need to install the module from the gallery, which is dead simple:

Install-Module ConvertTo-ShortenedPath -Scope CurrentUser

Lets perform a simple test:

001

As you see, the default behavior is to take the current location and shorten it with the default settings, which are:

  • KeepBefore: 2
  • KeepAfter: 1
  • MaxSegmentLength: NULL
  • TruncateFirstSegment: FALSE
  • TruncateLastSegment: FALSE
  • TruncateCharacter: …
  • ReplaceHome: TRUE
  • HomeCharacter: ~
  • Separator: <system default directory separator character>
  • OutputSeparator: NULL

Looking at the default settings we see that it will keep 2 sections before and 1 after any truncated path sections. But the ReplaceHome parameter being TRUE means that if you are in your users home folder, that part of the path will be replaced with the ~ character (Linux style).

Lets try from a path outside my home path:

002

Here we see that I have navigated 3 sub-folders deep from the root of the c-drive, and it’s quite apparent that we have 2 sections before and 1 section after the truncation character in the function output. The function counts the drive as a path section.

Lets define a path in a variable and try out some of the function parameters:

003

As you see, we can truncate the path segments by defining a maximum length for each section. The default behavior is to not truncate the first and the last segments, but we can enable this by using the TruncateFirstSegment (alias First) and TruncateLastSegment (alias Last) parameters.

If you want to truncate the segments length, but not the segments them self, you can achieve this by setting the KeepBefore (alias Before) and KeepAfter (alias After) to a high number:

004

The function also works on other types of paths. Lets demonstrate:

005

Notice that the Microsoft.PowerShell.Core\FileSystem:: part is automatically removed by the function, so you don’t have to do this manually in your custom prompt.

If you decide to try it out your self, check out how you can customize the output to your needs by playing with the different parameters available.

If you discover any bugs, or have any feature requests, please don’t hesitate to contact me in the comments section below or through Twitter.

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 )

Google+ photo

You are commenting using your Google+ 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