Tuesday, August 20, 2013

PowerShell 2.0 Type Accelerators

So at work I've been using PowerShell for things, because it's a fairly easy to learn scripting language that's grafted to the hip of .NET.  Specifically, PowerShell 2.0.  Yes, I know PowerShell 3.0 is a thing, and that there's a beta for 4.0.  I don't care.

One of the things in PowerShell 2.0 you might have noticed and/or used are the type accelerators.  Normally when you want to make a new object, you have to do something like this (using a stopwatch as an example):
$sw = new-object System.Diagnostics.Stopwatch
If there existed a type accelerator for System.Diagnostics.Stopwatch, that could be as easy as this:
$sw = new-object stopwatch
Well, the good news is, you can add your own type accelerators.  The doubly good news is, a type accelerator is a type of its own, so you can use a type accelerator to make adding type accelerators easier as well.  Sup dawg, I heard you like type accelerators.

The following doesn't apply if you use the PowerShell Community Extensions, where this already exists.  This is just a way for you to get equivalent functionality in vanilla PowerShell 2.0.

So, as implied above, we want to make a type accelerator for type accelerators.  This task is actually pretty simple.  Just plop this in your PowerShell profile (do echo $profile and create the file that comes up):
if( !( [type]::gettype( 'System.Management.Automation.TypeAccelerators' )::get.containskey( 'accelerators' ) ) ) { $_accel_type = [type]::gettype( 'System.Management.Automation.TypeAccelerators' ) $_accel_type::add( 'accelerators', $_accel_type ) remove-item Variable:_accel_type }
I will now proceed to explain it line by line.  The first line checks to see if there's a type accelerator called 'accelerators' already.  If it already exists, nothing will happen.  The whole point of this is so you can add other stuff to your profile and rerun it in the same session without getting errors.  The second line grabs the System.Management.Automation.TypeAccelerators type and stores it in a temporary variable.  The third line uses that variable's add static method to make a type accelerator for, you guessed it, type accelerators.  The fourth line simply removes our temporary variable.

After this has run (either restart PowerShell, or just run . $profile), or if you're using the PowerShell Community Extensions, the following is now possible:
Run that and PowerShell will poop out a list of all your available type accelerators.  Further type accelerators can be added using this type accelerator.  Returning to our example at the top:
[accelerators]::add( 'stopwatch', [System.Diagnostics.Stopwatch] )

No comments:

Post a Comment

I moderate comments because when Blogger originally implemented a spam filter it wouldn't work without comment moderation enabled. So if your comment doesn't show up right away, that would be why.