Remembering where you've been in Powershell with pushd and popd

The other day I discovered a long existing pair of commands in Powershell that allows one to navigate to a directory and then back to the previous one without having to manually maintain a stack of directories. The two commands are pushd and popd.

A quick bit of searching shows that these commands have existed in Unix shells for many years as well as Powershell since version 2. Wikipedia -- Pushd and popd

Where I have found this really useful recently is in deployment scripts where I need to change the current directory in the script but for usability I want to go back to where the script was first called from should any errors occur or even if the script finishes successfully. By using a try/catch/finally pattern this allows me to put the user back where they started with confidence whenever they execute the script.

try
{
pushd DIRECTORYPATH
# Logic goes here
}
catch
{
# Make sure any exceptions are bubbled up
throw $_
}
finally
{
popd
}

TechNet -- Push-Location
TechNet -- Pop-Location