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
To add a location to a location stack, use the Push-Location cmdlet. To get a location from a location stack, use the Pop-Location cmdlet. To display the locations in the current location stack, use the Stack parameter of the Get-Location cmdlet.
Stacks often are placed in the uppermost address regions of the machine. They usually grow from the highest memory location towards lower memory locations, allowing the maximum flexibility in the use of the memory between the end of program memory and the "top" of the stack.
Description. The Pop-Location cmdlet changes the current location to the location most recently pushed onto the stack by using the Push-Location cmdlet. You can pop a location from the default stack or from a stack that you create by using a Push-Location command.
In Windows PowerShell, pushd is a predefined command alias for the Push-Location cmdlet and popd is a predefined command alias for the Pop-Location cmdlet. Both serve basically the same purpose as the pushd and popd commands.
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\Keith
Although 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.:
cd $profile
In order to enable this functionality in PSCX you have to specify the Pscx.UserPreference.ps1 file when you import the module e.g.:
Import-Module PSCX -arg ~\Pscx.UserPreferences.ps1
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:
cd -?
or
man cd -full
The full source for this nested module is here (on CodePlex).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With