Sunday, January 29, 2017

Constructing generic-typed objects in PowerShell

Suppose you wanted to use an object of a generic .NET type in PowerShell, e.g. Dictionary. You might look for an extra switch on New-Object to specify the generic type's specialization, but there isn't one. The correct way to do it in modern PowerShell versions is this:

New-Object 'System.Collections.Generic.Dictionary[string,int]'

You can use either the full .NET names or the short PowerShell type names for the type parameters. The square bracketed part here is equivalent to the angle-bracketed part in C#. Also note that the quotes around the type name are required; if they're missing, PowerShell will interpret the parameter as the value of the -ComObject switch.

No comments:

Post a Comment