1

I need a function with the following requirements:

The function is assigned an unknown object. It is not known how many properties and / or sub-objects the object has. The function then iterates recursively through the object until it knows all the properties of the object.

PowerShell should then output this like a JSON file. But without the added characters ( { } [ ] , ).

I'm pretty sure the ConvertTo-Json cmdlet has such a function, but I can't script / use it myself.

Please format the whole thing with the cmdlet "Format-List" or something like that and not manually with tabs or spaces.

Here is a small example: Example object:

$Car = [PSCustomObject] @{
    Tire = [PSCustomObject] @{
        Color = "Black"
        Count = 4
    }
    
    Doors = [PSCustomObject]@{
        Color   = "Blue"
        Diameter = 21
    }
}

Output of a JSON file:

{
    "Tire":  {
                 "Color":  "Black",
                 "Count":  4
             },
    "Doors":  {
                  "Color":  "Blue",
                  "Diameter":  21
              }
}

Required output:

Tire: 
    Color:  Black
    Count:  4
Doors: 
    Color:      Blue
    Diameter:   21

The output should be saved in a string variable.

I've been researching for days, but can't find anything.

Thanks you so much.

Alex
  • 125
  • 2
  • 12
  • Does this answer your question? [Iterate over PSObject properties in PowerShell](https://stackoverflow.com/questions/37688708/iterate-over-psobject-properties-in-powershell) – Guenther Schmitz Sep 15 '20 at 07:07
  • Unfortunately that doesn't help me. @GuentherSchmitz – Alex Sep 15 '20 at 07:14
  • 2
    `I'm pretty sure the ConvertTo-Json cmdlet has such a function, but I can't script / use it myself.` What have you tried? How did it fail? You should (really) be able to get started by simply running `man ConvertTo-Json` and `man about_Comparison_Operators`. Your question, as is, doesn't show a whole lot of effort. – notjustme Sep 15 '20 at 08:27

1 Answers1

1

The output you are looking for above appears to be (at least close to) YAML syntax. You could use the 'powershell-yaml' module to output in the form that you need.

Make sure you have installed the 'powershell-yaml' module (Install-Module powershell-yaml) and then try to following:

Command

$Car = [PSCustomObject] @{
    Tire = [PSCustomObject] @{
        Color = "Black"
        Count = 4
    }
    
    Doors = [PSCustomObject]@{
        Color   = "Blue"
        Diameter = 21
    }
}

ConvertTo-Yaml $car

Output

Tire:
  Color: Black
  Count: 4
Doors:
  Color: Blue
  Diameter: 21

The output is the same as what you are looking for and ConvertTo-Yaml should work for all PSObjects.

ekeeling
  • 361
  • 1
  • 7