Search code examples
powershell

Directory Bookmarks in Powershell?


One of my favorite Bash tips involves creating aliases for marking and returning to directories as described here: http://www.huyng.com/archives/quick-bash-tip-directory-bookmarks/492/.

In Bash, it looks like this:

alias m1='alias g1="cd `pwd`"'

Is it possible to create a similar function in powershell?


Solution

  • You can add the following to the $profile:

    $marks = @{};
    
    $marksPath = Join-Path (split-path -parent $profile) .bookmarks
    
    if(test-path $marksPath){
    import-csv $marksPath | %{$marks[$_.key]=$_.value}
    }
    
    function m($number){
    $marks["$number"] = (pwd).path
    }
    
    function g($number){
    cd $marks["$number"]
    }
    
    function mdump{
    $marks.getenumerator() | export-csv $marksPath -notype
    }
    
    function lma{
    $marks
    }
    

    I didn't like the way of defining an alias for each like m1, m2 and so on. Instead you will be doing m 1 and g 1 etc.

    You can also add the line

    Register-EngineEvent PowerShell.Exiting –Action { mdump } | out-null
    

    so that it will do mdump when you exit the Powershell session. Unfortunately, doesn't work if you close the console window, but when you type exit.

    PS: Also have a look at CDPATH: CDPATH functionality in Powershell?