Sometimes you may need to create instances of generic classes in PowerShell.
Like this (in C#):
There is a generic class used in the code above: System.Collection.Generic.List.
If you want to create an instance of this class in PowerShell you can not use this:
You’ll receive an error!
Here is the solution: You can use the System.Type that represents other .NET types.
Use this PowerShell code snipped to create an instance of System.Collections.Generic.List<string>
“$o” will contain the created instance.
You can use this method for all other generic classes.
You may need to change the following details.
- In the first line of the snipped there is ‘`‘+"1" This is the amount of parameters for the generic class.
- In the second line you have to specify the parameter types for the generic class. Separate them with “,” and cast them to System.Type by using -as “Type”.
- In the third line you may need to specify the constructor parameters for creating an instance of the generic class.
Here is another example:
This creates an instance of System.Collections.Generic.SortedList<System.Int32, String> with a starting capacity of 10 (line 3: the second parameter of CreateInstance).