I have a class that I define in inline C# in powershell:
Add-Type -TypeDefinition @"
public class SomeClass {
string name;
public string Name { get { return name; } set { name = value; } }
int a, b;
public int A { get { return a; } set { a = value; } }
public int B { get { return b; } set { b = value; } }
}
"@
I can instantiate it:
$someClass= New-Object SomeClass -Property @{
‘Name’ = “Justin Dearing”;
“A” = 1;
“B” = 5;
};
But I cannot instantiate a list of it:
$listOfClasses = New-Object System.Collections.Generic.List[SomeClass];
Doing so gets me the following:
New-Object : Cannot find type [[System.Collections.Generic[SomeClass]]]: make sure the assembly containing this type is loaded.
At line:12 char:28
+ $listOfClasses = New-Object <<<< [System.Collections.Generic[SomeClass]]
+ CategoryInfo : InvalidType: (:) [New-Object], PSArgumentException
+ FullyQualifiedErrorId : TypeNotFound,Microsoft.PowerShell.Commands.NewObjectCommand
It seems that is not directly supported in PowerShell. Here is a solution, which provides a
New-GenericObjectscript; that does some reflection in order to create the correct type.