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

20 comments:

  1. Great, except - how does one keep the cd alias deleted? When I delete it, the function works fine, but after closing the prompt instance, the alias is always back. How did you solve this? I suppose I could add the remove-item command to the profile, but that seems a little strange.

    ReplyDelete
    Replies
    1. Try naming the function something other than 'cd', like 'cddash' for example. Then include the function in your powershell profile and add the following line:

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

      Delete
  2. Well, yeah you are right. If you close and reopen the powershell, the alias is always back.

    Unfortunately, We don't have any other option except adding Remove-Item cmdlet to the profile file :(

    ReplyDelete
  3. Good job, simple and elegant.
    Thanks.

    ReplyDelete
  4. Great job ! It is very simple and easy. Cd- is very simple command for changing previous working directory..

    ReplyDelete
  5. This comment has been removed by the author.

    ReplyDelete
  6. I have read so many rticles orr reviews concerning the blogger lovers except this piece of wrifing is really a fastidious article, keep itt up.



    my web page ... repossed cars land homes For sale in texas

    ReplyDelete
  7. As a newbie who comes from UNIX to powershell I really love these kinds of clear, clean tips. This is great, Thanks !!

    One other way I found to save the function is to use the following
    1. Save function in a file. I called mine function_cd_previous.ps1
    2. Then run this on the commandline
    . ''
    Note the SPACE between the and the

    e.g. . 'c:\powershell\function_cd_previous.ps1'

    There may be issues doing it this way. I'm not sure. Just trying to add to the collective :)

    ReplyDelete
  8. This is my version using pushd/popd:

    function cd-previous
    {
    if ($args[0] -eq '-')
    {
    popd
    }
    else
    {
    pushd $args[0]
    }
    }

    ReplyDelete
  9. I feel you look for something like Pop-Location (https://technet.microsoft.com/library/hh849842.aspx) and Push-Location (https://technet.microsoft.com/library/hh849855.aspx)

    ReplyDelete
  10. You can actually comment anonymously here.

    ReplyDelete
  11. i really likes your blog and You have shared the whole concept really well. and Very beautifully written,
    soulful read! thanks for sharing.
    gclub casino
    goldenslot casino
    goldenslot

    ReplyDelete
  12. Online casino superior level.
    บาคาร่าออนไลน์
    Our online casino. It's a widely spread web. Whether a gambler or a public interest in playing online casino. It is a website that offers services of joy. In the form of gambling games. With a variety of gambling games to choose from. There are also services. To cover the gambling style for you. More than imagined It is also the site with the largest number of participants to play online casino. With a high level of service responder Because the staff is there to help you with every problem you encounter 24 hours a day, without having to worry. Because only you join our site. Unless you are having fun then. You also have the opportunity to earn a fortune. Our website is a solid and reliable website. You can also access our website no matter where you are in the world. Do not wait too long Join us on our website.รูบี้888

    ReplyDelete
  13. More Betting Games
    Goldclub SlotThe site is open to play online casino in more thorough. No matter what you do Where to play in any time does not matter. You can access online casinos, choose different playing styles. Which has a variety of games. Variety of choices Everytime, anywhere And for you to choose to join the fun. In each game, it will have different playing tricks. Many are useless and ineffective. Different in each game. Because of that, the decision to gamble is up to you to decide who will play in what direction. But even the gimmick and skill will vary. You have the same goal: play for the win and hope for a return home. But playing online casinos. Indeed There are simple ways to play. To point your fate, you will bring money back home or you will lose 100% even if all the casinos want to bring back the money back home. But sometimes miss a chance. Because playing online casinos if you throw out in order to play the game. That means you have the opportunity to be a jackpot recipient. But at the same time, if you throw out. But luck is not with you. That means you have to be 100% unconditional as well. So if you do not want to lose all in an instant. You need to plan a play that will not only give you a lot of reward But it will allow you to enjoy and relax with the various forms of play. Yes, every time you click on a website. คาสิโนออนไลน์

    ReplyDelete
  14. ew casinos for you.
    Ruby888Online casino site Is a new online gambling game. You can access your mobile phone easily, quickly and safely. At the time you want At the time you want to relax and enjoy yourself. Without limiting whether you will ever play or not. We have games suitable for playmates. To a game that is suitable for gamblers. We have a style of play and how to play that will guide you. You do not have to worry. If you try to join us. You are entitled to receive a prize from our online casino. You do not have to travel far to casinos in foreign countries. We also have live broadcasts over high-speed internet that do not pose problems during your play or competition. And our online casino. High standards for high security. And feel free to join us. If you are interested in becoming a part of our online casino site today. You will have the privilege of having fun before anyone else. And is eligible for a grand prize of Jackpot Prize from each game. Try to be a part with us. Let's get to the website. IBCbet

    ReplyDelete
  15. The online gambling web site you need to try.
    รอยัล1688Our website is an online casino site with high security standards. And standards in every aspect and is another channel for online gambling. The largest number of users in the casino industry today. The game of online gambling is considered to be very appreciated with a system of audio and video services that are as sharp and clear as the player to play gambling in the casino really makes the player. Great choice to play gambling games online through fun, it does not have any difference in any way. So it is not uncommon nowadays that most gamblers choose to gamble online, rather than playing games. And for this reason, it makes our online casino site. It became known and popularized. And not only that, playing all-in-one online betting is another open source online betting game. With the advent of the casino industry. The fun of playing online gambling games comes with a fun and realistic service. It allows all players to play online casino games every time you come to the service and play games online betting site. viva3388

    ReplyDelete
  16. The fun of online casino games.
    Gclub SlotIs a g club website The leading online casino that is open to online gambling games that can win the hearts of gamblers because the casino gambling club is focused on playing gambling online standard. All online casino games are selected. And a good selection of online gambling games that are suitable for gamblers east. So nowadays, online casino websites are well-known and popular. Because today there are a number of gamblers who are quite selective to play casino games online through the Poipet website. The casino, because it is easy to access and play, and online casino games can also play in both mobile phones and on the computer. Gamblers can access and enjoy hundreds of online gambling games 24 hours a day, and you can always have fun at risk. I want to have a websiteHoliday Palace

    ReplyDelete