Saturday, 6 March 2010

Using Push-Location and Pop-Location in PowerShell

All popular shell environments have a wonderful tool named directory stack. It allows you to jump there and here in different directions and be able to return to some saved points. This feature really rules when you have to intensively work with command line. It’s really nice that PowerShell designers have implemented it with Push-Location and Pop-Location cmdlets. These cmdlets have standard pushd and popd aliases that are familiar to all *n?x and CMD gurus.

pushd is similar to cd with the only difference that it saves your previous location before moving to a new one. popd is a pair for pushd because it pops the last saved directory and changes your current directory to it. This concept is really simple, isn’t it? :)

So how to ease learning these commands? As for me I’ve:

1. Added my custom aliases to these commands

Set-Alias pd pushd
Set-Alias ppd popd

This allows me to use pushd as easy as cd. popd is a bit more complicated (1.5 times!) but it’s a good point for not losing your context accidentally.

2. Modified my prompt to display current directory stack depth

  $_locationStackDepthString = New-Object string ([char] '+'), (Get-Location -Stack).Count

Now each time when I dive deeper into directory stack I get a ‘+’ sign in front of my prompt and when I pop out I return to previous prompt state:

PowerShell pushd popd


No comments: