Home > OS >  Correctly nesting a PSCustomObject
Correctly nesting a PSCustomObject

Time:07-21

I've spent all day trying to figure this out.

I am trying to create a PSCustomObject that when exported to a Json file via ConvertTo-Json it will have this sort of structure:

{

    "Name":

    {

        "Trigger": "My Trigger",

        "Description": "Do this"        

        "body":

        [

            "Command one"

            "Command two"

            "Command three"

        ]

    }

}

This is how I am declaring my $PSCustomObject :

$myObject = [PSCustomObject]@{

    Name = @(

    Trigger = 'My Trigger'

    Description = 'Do this'

    body = @(

        'Command one'

        'Command two'

        'Command three'

    )

}

But when I try to run the above code, I am getting errors such as:

Trigger: 
Line |
   5 |          Trigger = 'My Trigger'
     |          ~~~~~~~
     | The term 'Trigger' is not recognized as a name of a cmdlet, function, script file, or executable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
Description: 

And any any variation I try just gives me more errors. Any help would be greatly welcome!

CodePudding user response:

If you're nesting [pscustomobject] instances, the same syntax applies to the outer and the inner instance, which, for object literals, is a [pscustomobject] cast applied to a hasthable literal:[1]

$myObject = [PSCustomObject] @{
  Name = [PSCustomObject] @{
    Trigger     = 'My Trigger'
    Description = 'Do this'
    body        = @(
      'Command one'
      'Command two'
      'Command three'
    )
  }
}

Alternatively, if the intent is to convert to JSON, consider [ordered] hasthable instances, which are comparatively more light-weight ([ordered] ensures that the definition order of the entries is preserved):

$myObject = [ordered] @{
  Name = [ordered] @{
    Trigger     = 'My Trigger'
    Description = 'Do this'
    body        = @(
      'Command one'
      'Command two'
      'Command three'
    )
  }
}

[1] Strictly speaking, no casting is involved: the syntax is syntactic sugar that directly constructs a [pscustomobject], as evidenced by the fact that the definition order of the hashtable entries is preserved, which stand-alone hashtable literals do not do.

  • Related