PowerShell Tricks - Trick 2
So this one is quite a handy one. Do you ever find yourself wanting to jump back and forth between folders? I have quite a few folders on my system (or on the network) that I use everyday. I wanted to have a way to quickly jump to each of these folders regardless where I am. At the same time, I wanted someway to be able to create such jump points whenever I want to.
The solution I came up with was to create functions that would change my location to the target folder I want to jump to. So I had a function I called “source” that would run “cd c:\source\” for instance. Then I took it one step ahead and created a function called “aliasthis” that would create such “jump” functions automatically.
To do that, I created a script file I called “aliases.ps1″. In it I added the following function:
1: function aliasthis($alias)
2: {
3: $path = (Get-Location).path;
4: if ($path.substring(1,1) -eq ‘:’)
5: {
6: $drive = $path.substring(0,2);
7: $script = “$drive ; cd `”$path`“”;
8: }
9: else
10: {
11: $script = “cd `”$path`“”
12: }
13:
14: $function = “function global:$alias { $script }”;
15: add-content $env:psconfig\\myscripts\\aliases.ps1 $function
16: new-item function:global:$alias -value “$script”;
17: }
To use that function, you type “aliasthis <aliasname>” and it will create a function with the name you specified that will take you to the location you ran the function from. So if you run it like this:
PS:c:\source> aliasthis source
It will create a function called “source” that will always take you to c:\source\.
The function does two things actually, it creates the function you want in the current shell session so you can use it right away, then
it adds the text of that function to the end of the aliases.ps1 file so that next time you start the shell, the function is available. So at the end of my aliases.ps1 file, I have stuff like:
function global:desktop { C: ; cd “C:Users\nazeehe\Desktop” }
Last, I make a call to aliases.ps1 from my profile.ps1 script to make sure this file gets loaded with every instance of the shell:
. aliases.ps1
That’s it! Works like a charm. I have quite a bit of jump functions declared now and I can make my way to any place on my PC or the network with just a few keystrokes!
Thanks for reading! I'd love to hear your thoughts, feel free to leave a comment below. Don't forget to subscribe to my RSS Feed!
May 18th, 2007 at 4:38 pm
We are all digging power shell also! I’m liking this little function. Thanks for sharing.