Working with type accelerators in PowerShell

Type accelerators are a great way in PowerShell to access .Net classes without having to write their full names. In essence they are aliases for .Net classes. If you have worked with PowerShell then you probably have used a type accelerator without knowing.

To get the list of available type accelerators the following command can be executed:

1
[psobject].Assembly.GetType("System.Management.Automation.TypeAccelerators")::Get

Depending on your version of PowerShell this will generate an output similar to this:

2016-02-26 (2)

Using the Get-TypeAccelerator function we can also display the available Type Accelerators in an easier to view way:

TypeAcc

It is useful for quickly defining objects without the complete notation of the class, for example compare the following two examples:

1
2
[System.Management.Automation.PSObject]@{'Property'='PowerShell Object'}
[pscustomobject]@{'Property'='PowerShell Object'}

Two type accelerators I use a lot are the [adsi] and [adsisearcher] Type Accelerators, this allows me to access and manipulate Active Dirclectory objects without relying on additional PowerShell modules. Here are some examples of querying Active Directory:

1
2
([adsisearcher]'samaccountname=jaap').FindOne()
[adsi]'LDAP://CN=Jaap,OU=AdminUsers,DC=JaapBrasser,DC=Com'

This allows for very short lines of code and used appropriately this can improve the readability of your code. Another few examples of type accelerators are the following:

1
2
3
4
[ipaddress]'8.8.8.8'
[version]'1.0.2.123'
[regex]::Replace('Type','e','e Accelerator')
[void] (Get-Process)

For more information on the different type and how to use them to define objects, queries or to access data you can view its article on MSDN. For example by executing the following code:

1
Start-Process -FilePath "http://social.msdn.microsoft.com/Search/en-US?query=$([psobject].Assembly.GetType("System.Management.Automation.TypeAccelerators")::Get.wmisearcher.ToString())"

There are a number of ways to use Type Accelerators in PowerShell, do you already use them and if so what are some of your favorite uses of them. Feel free to discuss them below in the comments section.

2 thoughts on “Working with type accelerators in PowerShell

  1. Thom Schumacher

    On of my Favorite Type accelerators is [uri].
    [uri]$u = ‘http://www.jaapbrasser.com/working-with-type-accelerators-in-powershell/’
    $u.host
    http://www.jaapbrasser.com
    $u.absolutepath
    /working-with-type-accelerators-in-powershell/
    $u.hostnametype
    Dns
    $u.port
    80

    That’s just some of the things you can do with the URI Accelerator.
    Makes it very nice also for parameter validation that way you always get a valid url.

    Reply

Leave a Reply

Your email address will not be published.