2

I want to create an object in PowerShell with one of its private members being a list or array of different objects. There are two important features for this request.

  1. The private member list or array must be able to grow dynamically (how would this work syntactically?)

  2. The solution must be backwards compatible with PowerShell 2.0. This means I can't create a custom class using the "class" keyword.

Is there a way this can be done in PowerShell?

2 Answers 2

2

are you looking for something like this (works in v2 ):

$x = New-Object psobject
$arr = new-object system.collections.arraylist
$arr.add("test")
$arr.add("test3")
$arr.add(@{"test4"="another1"})
$x | add-member -MemberType NoteProperty -Name arr -Value $arr
$x.arr.add("test5")
write-output $x.arr

by default arrays are polymorphic in powershell , so you can store any type in the array and pass it into the object

private members are not possible in v2 (PowerShell - how to add private members?)

Sign up to request clarification or add additional context in comments.

3 Comments

This may be the solution. I can't tell if the solution worked though because Write-Output has a hard time writing it all. Do you know how I can properly write the output (nicely) so that I would see the parent object with its array of smaller objects?
@wOxxOm I have updated the answer,thanks for the suggestion
@AlwaysQuestioning if you can add a sample output formatting ,then i can check for that
0

just do it:

#declaration array and variables differents types
$array=@()
$varstring='i am as tring'
$varint=0
$varobject=New-Object -TypeName "pscustomobject" @{val1="12"; val2="test"}

#add elements into array
$array+=$varstring
$array+=$varint
$array+=$varobject

#print array
$array

Comments

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.