How-to: Change Directory function CD -

In the bash shell, the command 'cd -' will jump to the previous working directory. To add this functionality to PowerShell, here is a simple cd function from Jagadish. This works by setting a global variable "OLDPWD"

Remove-Item Alias:cd

Function cd {
   if ($args[0] -eq '-') {
      $newdir=$OLDPWD;
   } else {
       $newdir=$args[0];
   }
   $before_change=Get-Location
   if ($newdir) {
      Set-Location $newdir;
   }
   Set-Variable -Name OLDPWD -Value $before_change -Scope global; 
 }

A more complex cd function is below, this stores the last directory/location for each drive/provider.
Windows remembers the current directory for each drive so you may find it more intuitive to also have the last directory remembered for each drive.

This function also demonstrates the use of Invoke-Expression to evaluate an expression where the VALUE of one variable ($tmp) contains the NAME of a second variable.

Remove-Item Alias:cd

function cd {
   [string]$drivepath = pwd; 
   $pwdletter = $drivepath.substring(0,1); 
   if ($args[0] -eq '-') {
      Set-Variable -Name tmp -Value "`$OLDPWD$pwdletter"; 
      $newdir = Invoke-Expression $tmp; 
      $newletter = '-' 
   } else {
      $newdir=$args[0]; 
      $newletter = ("$newdir  ").substring(1,1); 
   }

   $before_change=Get-Location; 
   if ($newdir -eq $null) {$newdir = '-'}

   if  (test-path $newdir) { 
      Set-Location $newdir; 
      if ($newletter -ne ':') { 
         Set-Variable -Name "OLDPWD$pwdletter" -Value $before_change -Scope global; 
      } 

   } else {
      # changing drive so dont store last dir 
      write-warning "Set-Location : Cannot find path [$newdir]"
   };
}

The function uses the first letter of each drive name to assign the variable, one for each drive:
OLDPWDc for the C drive, OLDPWDd for D: drive etc
This can also be used with the Registry and Certificate providers but using just one letter is not always a unique identifier i.e. Cert: will share a variable with C: and HKLM:/HKCU: share a variable with H: (fixing this is left as an exercise for the reader.)

Note: PowerShell does not save functions or aliases permanently by default. So if you close and reopen PowerShell, this function will no longer be available. To make it permanent, add the function to your PowerShell $Profile file.

“Web 1.0 was where corporations thought the internet was another dandy platform for telling us what they wanted us to know.
 Web 2.0 was where we showed them that the internet is about us, not them, and that if they want to stay around, they'd better sit back, shut up, and listen.
 Web 2.0, like Rock and Roll, is here to stay” ~ Ray Beckerman

Related PowerShell Cmdlets

Run a script - How to run a PowerShell script.


 
Copyright © 1999-2024 SS64.com
Some rights reserved