55

I am a Linux guy, but am trying to be open-minded and learn some Powershell. I miss the ability to cd - back to a previous directory, like in *nix shells. Is there a similar command in Powershell—one that would allow me to return to my previous directory?

2
  • 5
    If you were to use pushd to navigate to a new directory, you could popd back to the previous one. This works in Bash, PowerShell and even the legacy Windows command line.
    – Bob
    Commented May 10, 2013 at 16:11
  • 1
    Related (though not asking about Windows, PowerShell or a direct equivalent of this command, so not an exact duplicate): How can I change to the previous directory instead of going up?
    – Bob
    Commented May 11, 2013 at 16:55

9 Answers 9

12

I've had differing luck with cd +/- even though it should work.

pushd and popd have been around a long time and do the job nicely but I wasn't sure if they were officially supported in Powershell - I've just discovered they are actually aliases to Push-Location and Pop-Location so are current and supported, seems to be the best way to go:

https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.management/push-location?view=powershell-7 https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.management/pop-location?view=powershell-7

Previous suggested of using aliases to swap out the standard cd command are a good idea but in scripting I'm just using the real cmdlet name for clarity.

Example of what works:

cd B:\MyFolder\MySubFolder\
Push-Location
Set-Location Env:
cd B:\
Pop-Location

returns me to B:\MyFolder\MySubFolder\

Example of what does not work:

cd B:\MyFolder\MySubFolder\
Push-Location
Set-Location Env:
Pop-Location

fails - (requires the change in drive back to the where it was Pushed)

Push-Location and Pop-Location appears to be "LIFO" (Last In First Out)

2
  • 1
    the +/- options are new in cd so obviously you can't use it in older powershell versions
    – phuclv
    Commented May 13, 2021 at 2:54
  • 1
    OK so I have tested for a few minutes and once you move out of the drive you are in or at least into Env: the Pop-Location no longer works, but if you cd back to the Drive no matter where the Pop is available in that drive, so it looks like the individual drive stores its own Pushed Location. Commented Jul 5, 2023 at 3:43
24

Just tried cd - on Powershell Core 6.2.2 and it works :)

cd - takes you back through your location history

cd + takes you forward through your location history

1
  • 6
    help cd ... PowerShell 6.2 added support for '-' and '+' with the Path parameter. PowerShell maintains a history of the last 20 locations that can be [sic]access with - and +. This list is independent from the location stack that is accessed using the StackName parameter. Good catch! Commented Mar 19, 2020 at 20:36
21

Not in exactly the same fashion that I am aware of. One option is to use pushd instead of cd. Then popd will take you back.

You could also change your profile so that whenever a new prompt comes up (basically whenever you hit enter). It would get the PWD and compare that to the previous one. If they are different, then put that value onto a stack. Then you would include another function in your profile called something like cdb that would pop the last item off the stack and cd to it.

This sounded like fun so I came up with a solution. Put all this code into your profile (about_Profiles).

[System.Collections.Stack]$GLOBAL:dirStack = @()
$GLOBAL:oldDir = ''
$GLOBAL:addToStack = $true
function prompt
{
    Write-Host "PS $(get-location)>"  -NoNewLine -foregroundcolor Magenta
    $GLOBAL:nowPath = (Get-Location).Path
    if(($nowPath -ne $oldDir) -AND $GLOBAL:addToStack){
        $GLOBAL:dirStack.Push($oldDir)
        $GLOBAL:oldDir = $nowPath
    }
    $GLOBAL:AddToStack = $true
    return ' '
}
function BackOneDir{
    $lastDir = $GLOBAL:dirStack.Pop()
    $GLOBAL:addToStack = $false
    cd $lastDir
}
Set-Alias bd BackOneDir

Now you can cd just like normal and bd will take you back on location in your location history.

1
  • 14
    Or, you could just alias cd to pushd and bd to popd :P
    – Bob
    Commented May 11, 2013 at 10:09
3

I've modified EBGreen's great script so that cd- will always take you to your previous directory instead of reversing through your history. This way, using cd- multiple times will toggle between two directories - which is what cd - does on unix shells.

$GLOBAL:previousDir = ''
$GLOBAL:currentDir = ''
function prompt
{
    Write-Host "PS $(get-location)>"  -NoNewLine -foregroundcolor Green
    $GLOBAL:nowPath = (Get-Location).Path
    if($nowPath -ne $GLOBAL:currentDir){
        $GLOBAL:previousDir = $GLOBAL:currentDir
        $GLOBAL:currentDir = $nowPath
    }
    return ' '
}
function BackOneDir{
    cd $GLOBAL:previousDir
}
Set-Alias cd- BackOneDir

Oh and I had to change the prompt-color to green :)

2
  • 1
    If you replace cd $GLOBAL:previousDir to set-location, you can still save cd for an alias with pushd. Then you could have pushd mapped to cd, popd mapped to bd, and a functioning 'cd -' mapped to cd-. Best of all worlds until PS6.
    – Blaisem
    Commented Nov 29, 2020 at 12:55
  • 1
    Also, I didn't like the prompt line, so I changed that line to "PS " + $(get-location) + " [$(Get-Date -format yyMMdd-HH:mm:ss)]> "
    – Blaisem
    Commented Nov 29, 2020 at 12:56
3

Quick and dirty solution is to alias cd and bd to pushd and popd. A limitation is you can't do the equivalent of cd - over and over again.

Set-Alias -Name cd -Value pushd  -Option AllScope -Force
Set-Alias -Name bd -Value popd  -Option AllScope
1
  function custom_cd {
    if ($args.Count -eq 0) {
      $tmp_path = ${HOME}
    }
    elseif ($args[0] -eq '-') {
      $tmp_path = $OLDPWD;
    }
    else {
      $tmp_path = $args[0];
    }
    if ($tmp_path) {
      Set-Variable -Name OLDPWD -Value $PWD -Scope global;
      Set-Location $tmp_path;
    }
  }
  Set-Alias cd custom_cd -Option AllScope

Add this code to your $PROFILE. After that, the folowing features are available:

Command Description
cd takes you to the users home path
cd - switch to last location
cd <path> default behaviour of cd
1
  • It sets 'cd -' to return to the previous directory.
    – Blaisem
    Commented Nov 29, 2020 at 12:48
0

You can also search through your command history with control r, and find the previous time you entered the cd command.

1
  • 1
    That would work for a subset of the scenarios. As I tend to travel around with relative paths, it wouldn't work a lot of the time.
    – Kazark
    Commented Dec 6, 2019 at 21:18
0

I realize the question is old... but I still hit it in 2022 because I want the same feature but not hassle about extra commands.
I ended up installing PowerShell 7.2 and modifying my shortcuts to use this more recent version.

The profile though was in a different place, but a copy command of the ps5 profile did the trick, so everything looks the same as before with the bonus of "cd -" and "cd +"

Still baffles me why in friggin heavens it was decided that "cd -" was not good enough to keep flipping back and forth, but naaaaaaahhhh... someone had to put his stinking finger and say "let's use +" to accomplish the same thing.... ok, rant is over.

0

The easiest way I found is to use Push-Location and Pop-Location, especially in scripts.

Use Push-Location the same as you would use cd but it also puts your current directory on to the stack.

You can do this as many times as you want, as far as I know.

To go one level back, you just use Pop-Location

Push-Location c:\Windows\Sytem32\
ls
Pop-Location

Of course, you can make aliases for these commands as you like to shorten them for your needs.

1
  • Same answer has been proposed many years ago!
    – Toto
    Commented Nov 5, 2023 at 11:18

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .