Skip to content

Instantly share code, notes, and snippets.

@naiduv
Last active August 24, 2019 12:24
Show Gist options
  • Save naiduv/c975528f02aed8e20232dfb366b41e14 to your computer and use it in GitHub Desktop.
Save naiduv/c975528f02aed8e20232dfb366b41e14 to your computer and use it in GitHub Desktop.
powershell cd to $oldpwd - how to use cd minus in powershell

In powershell cd is an alias of set-location

get-command cd

That is set-location performs the same operations as cd.

Out of the box, set-location does not provide the minus functionality that takes us to the previous working directory.

To modify cd, we have to first remote the alias to set-location:

remove-item alias:cd

Then we need to create a new function cd as:

function cd { if ($args[0] -eq '-') { $pwd=$OLDPWD; } else { $pwd=$args[0]; } $tmp=pwd; if ($pwd) { Set-Location $pwd; } Set-Variable -Name OLDPWD -Value $tmp -Scope global; }

Making this easier to read:

function cd { 
  if ($args[0] -eq '-') { 
      $pwd = $oldpwd;
  }
  else {
     $pwd = $args[0];
  }
  $tmp = pwd;
  if($pwd){ 
     set-location $pwd;
  }
   
  set-variable -name oldpwd -value $tmp -scope global; 
}

making this work on every powershell window:

edit $profile using a text editor (similar to bash profile)

add the following:

remove-item alias:cd

function cddash { if ($args[0] -eq '-') { $pwd=$OLDPWD; } else { $pwd=$args[0]; } $tmp=pwd; if ($pwd) {
Set-Location $pwd; } Set-Variable -Name OLDPWD -Value $tmp -Scope global; }

set-alias -Name cd -value cddash -Option AllScope

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment