# PowerShell – Converting advanced object to flat object

PowerShell language allows you to work and build complicated objects. There are multiple ways to save them, such as XML or JSON, but sometimes using them is impossible or inadequate. Sometimes you want to use HTML or CSV or any other single dimension output.

blog

27 Feb 2022 en

![PowerShell – Converting advanced object to flat object](/wp-content/uploads/2022/02/img_620a1d96b6114.png)

[View images (7)](#pf-content-image-1-0)

**PowerShell** language allows you to work and build complicated objects. There are multiple ways to save them, such as **XML** or **JSON**, but sometimes using them is impossible or inadequate. Sometimes you want to use HTML or CSV or any other single dimension output.

### 💡 HTML Export for nested objects

Let's say you have an advanced **PowerShell** object with nested properties. It's a great feature of **PowerShell**, but displaying it to the user saving it as **CSV** or **HTML** will give you results that will not be very useful.

```powershell
$Object3 = [PSCustomObject] @{
    "Name"    = "Przemyslaw Klys"
    "Age"     = "30"
    "Address" = @{
        "Street"  = "Kwiatowa"
        "City"    = "Warszawa"

        "Country" = [ordered] @{
            "Name" = "Poland"
        }
        List      = @(
            [PSCustomObject] @{
                "Name" = "Adam Klys"
                "Age"  = "32"
            }
            [PSCustomObject] @{
                "Name" = "Justyna Klys"
                "Age"  = "33"
            }
        )
    }
    ListTest  = @(
        [PSCustomObject] @{
            "Name" = "Justyna Klys"
            "Age"  = "33"
        }
    )
}

$Object4 = [PSCustomObject] @{
    "Name"    = "Przemyslaw Klys"
    "Age"     = "30"
    "Address" = @{
        "Street"  = "Kwiatowa"
        "City"    = "Warszawa"
        "Country" = [ordered] @{
            "Name" = "Gruzja"
        }
        List      = @(
            [PSCustomObject] @{
                "Name" = "Adam Klys"
                "Age"  = "32"
            }
            [PSCustomObject] @{
                "Name" = "Pankracy Klys"
                "Age"  = "33"
            }
            [PSCustomObject] @{
                "Name" = "Justyna Klys"
                "Age"  = 30
            }
            [PSCustomObject] @{
                "Name" = "Justyna Klys"
                "Age"  = $null
            }
        )
    }
    ListTest  = @(
        [PSCustomObject] @{
            "Name" = "Sława Klys"
            "Age"  = "33"
        }
    )
    MoreProperties = $true
}
```

```powershell
$Object3, $Object4 | Out-HtmlView -Filtering
```

[!\[Out-HtmlView rendering nested PowerShell objects with unreadable embedded properties before flattening\](/wp-content/uploads/2022/02/img_62094f1029e03.png)](/wp-content/uploads/2022/02/img_62094f1029e03.png)

While Name and Age properties output was proper, the rest – not so much.

### 💡 Export-CSV for nested objects

The same problem will be visible in the Export-CSV command.

```powershell
$Object3, $Object4 | Export-Csv -Path "$PSScriptRoot\test.csv" -NoTypeInformation
```

[!\[Exported CSV view showing nested PowerShell object properties collapsed into hard-to-read values\](/wp-content/uploads/2022/02/img_6209509328613.png)](/wp-content/uploads/2022/02/img_6209509328613.png)

### 💡 Converting Advanced PowerShell object to flat objects

While you can always use JSON and XML as mentioned to save files – wouldn't it be nice to have another option? This is where **ConvertTo-FlatObjec**t comes in! It converts advanced objects into flat ones.

```powershell
$Object3, $Object4 | ConvertTo-FlatObject | Export-Csv -Path "$PSScriptRoot\test.csv" -NoTypeInformation -Encoding UTF8
```

[!\[CSV output after ConvertTo-FlatObject expands nested properties into flat columns\](/wp-content/uploads/2022/02/img_620954e7e4b69.png)](/wp-content/uploads/2022/02/img_620954e7e4b69.png)

The same goes for **Out-HTMLView** and **New-HTMLTable **from [PSWriteHTML](https://github.com/EvotecIT/PSWriteHTML) module. As part of the module, I've added a parameter called `FlattenObject` which internally uses **ConvertTo-FlatObject **to make it easy for end-users.

```powershell
$Object3, $Object4 | Out-HtmlView -Filtering -FlattenObject
```

[!\[Out-HtmlView table after FlattenObject makes nested properties readable and filterable\](/wp-content/uploads/2022/02/img_620959e85ad5f.png)](/wp-content/uploads/2022/02/img_620959e85ad5f.png)

### 💡 Office 365 Example of using ConvertTo-FlatObject inside Out-HTMLView

If you're wondering what it could be useful for – let me give you an example. Get-AzureADAuditSignInLogs is a cmdlet from Office 365 to get information about logging in users to Office 365.

```powershell
Connect-AzureAD
$Logins = Get-AzureADAuditSignInLogs
$Logins[0]
```

[!\[Sample Office 365 sign-in log object from Get-AzureADAuditSignInLogs with nested properties\](/wp-content/uploads/2022/02/img_620a56dd93d67.png)](/wp-content/uploads/2022/02/img_620a56dd93d67.png)

This means that once you push it to **CSV** or **HTML** using **Out-HTMLView**, all those nested properties would be hidden away or mainly unreadable, unsortable.

[!\[HTML view of Office 365 sign-in logs before flattening, with nested values difficult to read\](/wp-content/uploads/2022/02/img_620a582fe6b1d.png)](/wp-content/uploads/2022/02/img_620a582fe6b1d.png)

As you see above – it's far from perfect. I would usually take my PowerShell skills and convert those advanced objects into smaller, one-dimensional objects to display exactly what I wanted. If I had 50 columns, I would rebuild the thing entirely, and it would take some time to do it. Or I would use new functionality and just like that, with a single line of code get it all in one go.

```powershell
$Logins | Out-HtmlView -ScrollX -Filtering -FlattenObject
$Logins | Out-HtmlView -ScrollX -Filtering -FlattenObject -ExcludeProperty "*IsReadOnly","*Count"
```

[!\[HTML view of Office 365 sign-in logs after FlattenObject expands nested properties into readable columns\](/wp-content/uploads/2022/02/img_620a5951474ab.png)](/wp-content/uploads/2022/02/img_620a5951474ab.png)

Notice that I'm using ExcludeProperty to filter out some columns that are often part of the object that I don't want to see. Isn't it much nicer? Easily readable, zero effort. Report ready in 15 minutes.

### 💡 Installing PSSharedGoods

ConvertTo-FlatObject is part of the [PSSharedGoods](https://github.com/EvotecIT/PSSharedGoods) PowerShell module. This is my “glue” module with loads of functions. It contains over 200 functions that allow me to reuse those when needed. How do you install it? The easiest and most optimal way is to use **PowerShellGallery**. This will get you up and running in no time. Whenever there is an update, just run **Update-Module,** and you're done.

```powershell
Install-Module PSSharedGoods
# Update-Module PSSharedGoods
```

If you prefer **New-HTMLTable** or **Out-HTMLView** commands, you may want to install [PSWriteHTML](https://github.com/EvotecIT/PSWriteHTML) instead.

```powershell
Install-Module PSWriteHTML
# Update-Module PSWriteHTML
```

However, if you're into code – want to see how everything is done, you can use **GitHub** sources. Please keep in mind that the **PowerShellGallery** version is optimized and better for production use. If you see any issues, bugs, or features that are missing, please make sure to submit them on **GitHub**.

- 💬 Code is published as a module on [PowerShellGallery](https://www.powershellgallery.com/packages/PSTeams/)
- 💬 Issues should be reported on [GitHub](https://github.com/EvotecIT/PSTeams/issues)
- 💬 Code is published on [GitHub](https://github.com/EvotecIT/PSTeams)

### 💡 Direct source code for ConvertTo-FlatObject

If you don't like using modules, you can use code directly.

```powershell
Function ConvertTo-FlatObject {
    .1, .2, .3, …
    - 0, arrays will be 0 based: .0, .1, .2, …
    - "", the first item in an array will be unnamed and than followed with 1: , .1, .2, …

    .PARAMETER Depth
    The maximal depth of flattening a recursive property. Any negative value will result in an unlimited depth and could cause a infinitive loop.

    .PARAMETER Uncut
    The maximal depth of flattening a recursive property. Any negative value will result in an unlimited depth and could cause a infinitive loop.

    .EXAMPLE
    $Object3 = [PSCustomObject] @{
        "Name"    = "Przemyslaw Klys"
        "Age"     = "30"
        "Address" = @{
            "Street"  = "Kwiatowa"
            "City"    = "Warszawa"

            "Country" = [ordered] @{
                "Name" = "Poland"
            }
            List      = @(
                [PSCustomObject] @{
                    "Name" = "Adam Klys"
                    "Age"  = "32"
                }
                [PSCustomObject] @{
                    "Name" = "Justyna Klys"
                    "Age"  = "33"
                }
                [PSCustomObject] @{
                    "Name" = "Justyna Klys"
                    "Age"  = 30
                }
                [PSCustomObject] @{
                    "Name" = "Justyna Klys"
                    "Age"  = $null
                }
            )
        }
        ListTest  = @(
            [PSCustomObject] @{
                "Name" = "Sława Klys"
                "Age"  = "33"
            }
        )
    }

    $Object3 | ConvertTo-FlatObject

    .NOTES
    Based on https://powersnippets.com/convertto-flatobject/
    #>
    [CmdletBinding()]
    Param (
        [Parameter(ValueFromPipeLine)][Object[]]$Objects,
        [String]$Separator = ".",
        [ValidateSet("", 0, 1)]$Base = 1,
        [int]$Depth = 5,
        [Parameter(DontShow)][String[]]$Path,
        [Parameter(DontShow)][System.Collections.IDictionary] $OutputObject
    )
    Begin {
        $InputObjects = [System.Collections.Generic.List[Object]]::new()
    }
    Process {
        foreach ($O in $Objects) {
            $InputObjects.Add($O)
        }
    }
    End {
        If ($PSBoundParameters.ContainsKey("OutputObject")) {
            $Object = $InputObjects[0]
            $Iterate = [ordered] @{}
            if ($null -eq $Object) {
                #Write-Verbose -Message "ConvertTo-FlatObject - Object is null"
            } elseif ($Object.GetType().Name -in 'String', 'DateTime', 'TimeSpan', 'Version', 'Enum') {
                $Object = $Object.ToString()
            } elseif ($Depth) {
                $Depth--
                If ($Object -is [System.Collections.IDictionary]) {
                    $Iterate = $Object
                } elseif ($Object -is [Array] -or $Object -is [System.Collections.IEnumerable]) {
                    $i = $Base
                    foreach ($Item in $Object.GetEnumerator()) {
                        $Iterate["$i"] = $Item
                        $i += 1
                    }
                } else {
                    foreach ($Prop in $Object.PSObject.Properties) {
                        if ($Prop.IsGettable) {
                            $Iterate["$($Prop.Name)"] = $Object.$($Prop.Name)
                        }
                    }
                }
            }
            If ($Iterate.Keys.Count) {
                foreach ($Key in $Iterate.Keys) {
                    ConvertTo-FlatObject -Objects @(, $Iterate["$Key"]) -Separator $Separator -Base $Base -Depth $Depth -Path ($Path + $Key) -OutputObject $OutputObject
                }
            } else {
                $Property = $Path -Join $Separator
                $OutputObject[$Property] = $Object
            }
        } elseif ($InputObjects.Count -gt 0) {
            foreach ($ItemObject in $InputObjects) {
                $OutputObject = [ordered]@{}
                ConvertTo-FlatObject -Objects @(, $ItemObject) -Separator $Separator -Base $Base -Depth $Depth -Path $Path -OutputObject $OutputObject
                [PSCustomObject] $OutputObject
            }
        }
    }
}
```

## Related Projects

Projects that align with this post's tags, categories, and content.

[All projects](/projects/)

Matching projects...

[Back to Blog](/blog)

## Related posts

- [Office 365 Health Service using PowerShell](/blog/office-365-health-service-using-powershell/)
- [Creating Office 365 Migration Diagram with PowerShell](/blog/creating-office-365-migration-diagram-with-powershell/)
- [Syncing Global Address List (GAL) to personal contacts and between Office 365 tenants with PowerShell](/blog/syncing-global-address-list-gal-to-personal-contacts-and-between-office-365-tenants-with-powershell/)

<!-- PowerForge markdown artifact sha256:91FD30F21C6E7731751C9E2135DC9B04C654AD415E06A081302884DD8A35F82D -->
