4

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.

2
  • 1
    New-Object PSObject -Property $hash Commented Jul 31, 2018 at 19:28
  • Any reason for limiting yourself to v2? Commented Jul 31, 2018 at 21:44

1 Answer 1

4

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;
  }
"@
Sign up to request clarification or add additional context in comments.

1 Comment

Super! Thanks! (I swear I had tried the hash table option and got an error, but it's working now!)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.