0

I'm generating an object which contains the results of some diagnostics process. It has the following structure:

ProdVersion    : [string]
LastAttempted  : [ordered hashtable]
LastSuccessful : [ordered hashtable]
Pings      : [array of hashtables]
Ports      : [array of hashtables]
Services       : [array of hashtables]
     $ServiceProps = [ordered]@{
         ServiceName = $sName
         Exists = $sExists
         Disabled = $sDisabled
         Status = $sStatus}

One such object represents data for one CI (server). I want to output this object in a 'linarized' form for CSV report, as a line of the following format: 'name:val;name:val;name:val...' where val (if a collection) items are in turn separated with, let's say, ','.

What would be the most elegant approach? I'm lloking for a generic solution not bound to my particular object structure.

Update

right now I'm trying smth like this, it works but doesn't include the last 'Services' part in output, can't figure out why -

$output = New-Object System.Text.StringBuilder

function expand ($object) {
    foreach ($i in $object.keys) {
        $t = $object.$i.gettype()
        if ($t -in ([System.Object[]], [System.Collections.Specialized.OrderedDictionary])) {
            expand $object.$i
        } else {
            [void]$output.Append("$i=$($object.$i);")
        }
    }
}

Update 2

Found out why - it treats key values in $ServiceProps (e.g., ServiceName) not as [string] but as [Object[]], and tries to iterate through its .Keys, which is $null.

Max
  • 71
  • 1
  • 7
  • Possible duplicate of [PowerShell convert nested JSON array into separate columns in CSV file](https://stackoverflow.com/questions/45829754/powershell-convert-nested-json-array-into-separate-columns-in-csv-file) – Tomek Jul 30 '18 at 10:18

1 Answers1

0

Object serialization is the word you're looking for. You can use Export-Clixml cmdlet. It will write the object into xml document. The other option is to use ConvertTo-Json -Compress. It'll output a single line. But if you need this line to be exactly in specified format, then I guess there's no other way than to write your own function.

AdamL
  • 11,328
  • 5
  • 49
  • 72
  • I can't use Json cmdlets (I know about system.web.script.serialization.javascriptSerializer though) becasue of compatibility with PS 2.0. Of course, I meant custom function for serialization, not the built-in cmdlets. I don't see how Export-CliXML will help me. – Max Jul 30 '18 at 11:58