Reputation: 403
Warning: I am looking to do this in PowerShell v2 (sorry!).
I would like to have a custom object (possibly created as a custom type) that has an array property. I know how to make a custom object with "noteproperty" properties:
$person = new-object PSObject
$person | add-member -type NoteProperty -Name First -Value "Joe"
$person | add-member -type NoteProperty -Name Last -Value "Schmoe"
$person | add-member -type NoteProperty -Name Phone -Value "555-5555"
and I know how to make a custom object from a custom type:
Add-Type @"
public struct PersonType {
public string First;
public string Last;
public string Phone;
}
"@
$person += New-Object PersonType -Property @{
First = "Joe";
Last = "Schmoe";
Phone = "555-5555";
}
How can I create a custom object with a type that includes an array property? Something like this hash table, but as an object:
$hash = @{
First = "Joe"
Last = "Schmoe"
Pets = @("Fluffy","Spot","Stinky")
}
I'm pretty sure I can do this using [PSCustomObject]$hash
in PowerShell v3, but I have a need to include v2.
Thanks.
Upvotes: 4
Views: 15734
Reputation: 47802
When you use Add-Member
to add your note properties, the -Value
can be an array.
$person | add-member -type NoteProperty -Name Pets -Value @("Fluffy","Spot","Stinky")
If you want to create the properties as a hashtable first, like your example, you can pass that right into New-Object
as well:
$hash = @{
First = "Joe"
Last = "Schmoe"
Pets = @("Fluffy","Spot","Stinky")
}
New-Object PSObject -Property $hash
Your PersonType
example is really written in C#, as a string, which gets compiled on the fly, so the syntax will be the C# syntax for an array property:
Add-Type @"
public struct PersonType {
public string First;
public string Last;
public string Phone;
public string[] Pets;
}
"@
Upvotes: 4