Adding Type Accelerators

by Jul 27, 2012

Type accelerators are shortcut names that represent .NET types. For example, you can use [XML] instead of [System.Xml.XmlDocument]. By default, PowerShell only contains type accelerators for the most common .NET types but you can easily add more.

The following sample adds a type [SuperArray] which is a shortcut to [System.Collections.ArrayList] and creates a super-charged array: it has methods to insert and add new elements, speeding up array-manipulation tremendously:

PS> $accelerator = [type]::gettype("System.Management.Automation.TypeAccelerators")
PS> $accelerator::Add('SuperArray', [System.Collections.ArrayList])
PS> $arr = [SuperArray](1,2,3,4,5)
PS> $arr.Insert(1,12)
PS> $arr
1
12
2
3
4
5

Note that this trick will no longer work in PowerShell v3 unfortunately.

Twitter This Tip! ReTweet this Tip!