Max
Max

Reputation: 81

How to 'flatten' complex Powershell object (hashtable) for output as CSV entry?

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.

Upvotes: 0

Views: 3496

Answers (1)

AdamL
AdamL

Reputation: 13141

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.

Upvotes: 1

Related Questions