Change directory to previous directory in Powershell

Solution 1:

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.

Solution 2:

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.