Skip to content

Instantly share code, notes, and snippets.

@SP3269
Last active February 21, 2023 06:25
Show Gist options
  • Save SP3269/fb5b0784bf2cede11ac3a1fa6d5ee1de to your computer and use it in GitHub Desktop.
Save SP3269/fb5b0784bf2cede11ac3a1fa6d5ee1de to your computer and use it in GitHub Desktop.
Flattening structures in PowerShell

Quickly coding a function that allows flattening a structure. The goal is to use in comparing complex structures, such as created by the ConvertFrom-JSON or ConvertFrom-Yaml.

Outputs a hash table.

Example:

$res = Flatten-Object @{SH = @("bin", "bash"); A = 1; B = "ZZ"; C = @{CC = "CC"}; Logic = $true}
$res.Keys | Sort-Object | % { Write-Output "$_ = $($res[$_])"}

Outputs:

.A = 1
.B = ZZ
.C.CC = CC
.Logic = True
.SH[0] = bin
.SH[1] = bash
function Flatten-Object ( $obj, [string] $prefix = "" ) {
[CmdletBinding()]
$res = @{}
Write-Verbose $prefix
if ($null -eq $obj) {
return @{$prefix = "null"}
}
switch -Regex ($obj.GetType().Name )
{
'^(Boolean|String|Int32|Int64|Float|Double)$' {
$res += @{$prefix = $obj}
}
"Hashtable" {
$obj.GetEnumerator() | ForEach-Object {
$res += Flatten-Object $_.Value ($prefix+"."+$_.Key)
}
}
'^(List.*|.+\[\])$' {
$i = 0
foreach ( $entry in $obj ) {
$ind = $prefix + "[$i]"
$res += Flatten-Object $entry $ind
$i++
}
}
}
$res
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment