Lets say I define the following classes in C# inside a powershell script:
Add-Type -TypeDefinition @"
public class InnerClass {
int a, b;
public int A { get { return a; } set { a = value; } }
public int B { get { return b; } set { b = value; } }
}
public class SomeClass {
string name;
public string Name { get { return name; } set { name= value; } }
InnerClass numbers;
public InnerClass Numbers { get { return numbers; } set { numbers = value; } }
}
"@
I can instantiate an instance of InnerClass
like so:
New-Object InnerClass -Property @{
'A' = 1;
'B' = 2;
}
However, if I want to instantiate SomeClass
and set the properties for InnerClass
in a similar manner, it fails.
New-Object SomeClass -Property @{
'Name' = "Justin Dearing";
Numbers = @{
'A' = 1;
'B' = 2;
};
} ;
New-Object : The value supplied is not valid, or the property is read-only. Cha
nge the value, and then try again.
At line:20 char:11
+ New-Object <<<< SomeClass -Property @{
+ CategoryInfo : InvalidData: (:) [New-Object], Exception
+ FullyQualifiedErrorId : InvalidValue,Microsoft.PowerShell.Commands.NewOb
jectCommand
Name : Justin Dearing
Numbers :
Is there anyway to set SomeClass
, including the properties of Numbers
in one New-Object statement?
You can't directly but you can have the innerclass constructed inline with
New-Object SomeClass -Property @{
'Name' = "Justin Dearing";
'Numbers' = New-Object InnerClass -Property @{
'A' = 1;
'B' = 2;
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With