Saturday, July 4, 2009

Change to Previous Working Directory in Powershell (cd -)

One of the cool features of linux bash is the ability to go to the previous working directory. In Bash, we can go to the previous working directory using "cd -" command.

Unfortunately, we do not have an equivalent of "cd -" in Powershell. So I just wrote a simple powershell cd function for this cool feature

Powershell CD function:

1function cd {
2
3 if ($args[0] -eq '-') {
4 $pwd=$OLDPWD;
5 } else {
6 $pwd=$args[0];
7 }
8
9 $tmp=pwd;
10
11 if ($pwd) {
12 Set-Location $pwd;
13 }
14
15 Set-Variable -Name OLDPWD -Value $tmp -Scope global;
16}


Now lets see, how to install the above function in your powershell

Step 1: Remove Alias for cd

   cd is actually not a powershell cmdlet. It is an *alias* to Set-Location cmdlet. To install our new cd function, first we need to remove this alias


PS C:\Scripts> Get-Command cd

CommandType Name Definition
----------- ---- ----------
Alias cd Set-Location

PS C:\Scripts> Remove-Item Alias:cd
PS C:\Scripts>

Step 2: Install Powershell cd function

   We have removed the alias for cd. Now we can just go ahead and install our new powershell cd function which is very easy. Just paste the complete function in one line.

Powershell CD function in one line:


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; }



PS C:\Scripts> 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; }
PS C:\Scripts>
PS C:\Scripts> Get-Item function:cd

CommandType Name Definition
----------- ---- ----------
Function cd if ($args[0] -eq '-') { $pwd=$OLDPWD; } else { ...

Ready to go, Lets see this cool feature in action


PS C:\Scripts> cd C:\Users\Jagadish\Desktop
PS C:\Users\Jagadish\Desktop> cd -
PS C:\Scripts> cd -
PS C:\Users\Jagadish\Desktop> cd ..\Documents
PS C:\Users\Jagadish\Documents> cd C:\Scripts
PS C:\Scripts> dir

Directory: C:\Scripts

Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 6/6/2009 12:14 PM 279 test.ps1
-a--- 6/20/2009 8:27 PM 69 test1.ps1

PS C:\Scripts> cd -
PS C:\Users\Jagadish\Documents>

Hope you like it :)

Note: Powershell will not save any functions/aliases by default. So if you close your powershell and reopen it, this function will not be available. To make it permanent, it should be added in the Windows Powershell Profile file