In PowerShell you can use pushd (an alias for Push-Location) and popd (an alias for Pop-Location) to push items onto and pop items off of a location stack.
This is very similar to bash’s pushd and popd functionality for a stack of directories.
But one other nice feature of bash is that you can use pushd all by itself to swap the top two locations on the stack. So you can flip back and forth very quickly between one location and another. And it also takes an argument like pushd +3 so you can swap with a location that’s a few elements down in your stack.
Is there any way to do this with PowerShell?
As an example, in bash:
$ pwd
/bin
$ pushd ~
~ /bin
$ pwd
/home/hopper
$ pushd
/bin ~
$ pwd
/bin
$ pushd
~ /bin
$ pwd
/home/hopper
There has been similar functionality built into the PowerShell Community Extensions for years 🙂 e.g.:
48 > cd C:\inetpub C:\inetpub 49 > cd C:\Windows\System32 C:\Windows\System32 50 > cd - C:\inetpub 51 > cd + C:\Windows\System32 52 > cd # Directory Stack: --- ---------------- 0 C:\Users\Keith 1 C:\inetpub -> 2 C:\Windows\System32 53 > cd -0 C:\Users\KeithAlthough it isn’t quite a swap, the backward (-) and forward (+) metaphor is pretty well established these days. And you skip to any location in the location history by specifying
-<num>. In fact, and this was a very handy addition suggested by a PSCX user, you can CD to a file file (which just cds to the dir the file is in) e.g.:In order to enable this functionality in PSCX you have to specify the Pscx.UserPreference.ps1 file when you import the module e.g.:
In this case, I copy the file from the PSCX dir to my home dir and modify to suit my tastes. For more info execute:
or
The full source for this nested module is here (on CodePlex).