Need Help assigning an embedded Object to a parent Object in a PowerShell script

I am rather new to PowerShell and I'm sure the script gods will have a hay day picking this apart, or reject it out of hand. I have read a lot of documentation regarding creating objects, and assigning members to the objects. A lot of posts are very similar, but I have yet to find one that answers my question directly.

The following is an example of what I'm trying to achieve.

$MGSet = New-Object -TypeName PSObject
$MgmtSet = New-Object -TypeName Cmdlet.WebService.MgInfo
      $MgmtSet.Param1 = $true
      $MgmtSet.Param2 = $false
      $MgmtSet.oParam = [Cmdlet.WebService.ParamBase] @{
            $PB.differentParam = "Testname"
            $PB.DiffParam2 = $false
            $PB.oDifParamOb = Add-Member -InputObject $MGset - MemberType NoteProperty -Name oDifParamOb -Value ("sys1", "Sys2", "Sys3")

First I know this is wrong, but the idea is the Parent object has an object as one of the parameters. Furthermore, the new object also has an embedded object: Parentobject > childobject > baseobject

If I were to execute ...

$MgmtSet = New-Object -TypeName Cmdlet.WebService.MgInfo

I would get

ExtensionData                       :
Param1                              : True
Param2                              : False
oParam                              : {Cmdlet.WebService.ParamBase}

On the same token if I execute

$MgmtSet = New-Object -TypeName Cmdlet.WebService.ParamBase

I would get

ExtensionData                       :
differentParam                      : Testname
DiffParam2                          : False
oDifParamOb                         : 

The goal is to assign values to the embedded objects and pass it to the parent object. I can use an Array, or a Hash table, but assigning those objects to the parent is where I fall short.

Thank you ahead of time.

2 answers

  • answered 2018-11-08 00:40 BaronW

    Is this what you want?

    $ParentObject = New-Object -TypeName psobject
    $ChildObject = New-Object -TypeName psobject
    $ChildObject | Add-Member -MemberType NoteProperty -Name "HI" -Value "Spoons are fun"
    $ParentObject | Add-Member -MemberType NoteProperty -Name "Sub" -Value $ChildObject

  • answered 2018-11-08 04:01 mklement0

    Since both types involved seem to have parameter-less constructors, initializing them via hashtables should work; similarly, custom object $MGSet can be created inline by casting a hashtable to [pscustomobject]:

    $MgmtSet = [Cmdlet.WebService.MgInfo] @{
       Param1 = $true
       Param2 = $false
       oParam = [Cmdlet.WebService.ParamBase] @{
         differentParam = "Testname"
         DiffParam2 = $false
         oDifParamOb = [pscustomobject] @{ oDifParamOb = "sys1", "Sys2", "Sys3" }