| | | 1 | | <# |
| | | 2 | | .SYNOPSIS |
| | | 3 | | Recursively normalizes a value into a form suitable for Dictionary[string, object]. |
| | | 4 | | .DESCRIPTION |
| | | 5 | | Recursively normalizes a value into a form suitable for Dictionary[string, object]. |
| | | 6 | | - Unwraps PSObject shells |
| | | 7 | | - Converts IDictionary to Dictionary[string, object] |
| | | 8 | | - Converts IEnumerable (except string) to List[object] |
| | | 9 | | - Primitives and POCOs are returned as-is |
| | | 10 | | .PARAMETER Value |
| | | 11 | | The value to normalize. |
| | | 12 | | .PARAMETER Depth |
| | | 13 | | Current recursion depth to prevent infinite loops. |
| | | 14 | | .PARAMETER MaxRecursionDepth |
| | | 15 | | Maximum recursion depth. Defaults to 8. |
| | | 16 | | .OUTPUTS |
| | | 17 | | The normalized value or $null if the input is $null or could not be normalized. |
| | | 18 | | .NOTES |
| | | 19 | | Limits recursion depth to 8 levels. |
| | | 20 | | #> |
| | | 21 | | function _NormalizeValueToDictionary([object]$Value, [int]$Depth, [int]$MaxRecursionDepth = 8) { |
| | 0 | 22 | | if ($null -eq $Value) { return $null } |
| | 0 | 23 | | if ($Depth -gt $MaxRecursionDepth) { return ($Value.ToString()) } |
| | | 24 | | |
| | | 25 | | # Unwrap PSObject shell |
| | 0 | 26 | | if ($Value -is [System.Management.Automation.PSObject]) { |
| | 0 | 27 | | $base = $Value.BaseObject |
| | 0 | 28 | | if ($null -eq $base -or $base -eq $Value) { return $Value.ToString() } |
| | 0 | 29 | | return _NormalizeValueToDictionary $base ($Depth + 1) |
| | | 30 | | } |
| | | 31 | | |
| | | 32 | | # Hashtable / IDictionary → new Dictionary[string, object] |
| | 0 | 33 | | if ($Value -is [System.Collections.IDictionary]) { |
| | 0 | 34 | | $out = [System.Collections.Generic.Dictionary[string, object]]::new() |
| | 0 | 35 | | foreach ($key in $Value.Keys) { |
| | 0 | 36 | | if ([string]::IsNullOrWhiteSpace([string]$key)) { continue } |
| | 0 | 37 | | $nv = _NormalizeValue $Value[$key] ($Depth + 1) |
| | 0 | 38 | | if ($null -ne $nv) { $out[[string]$key] = $nv } |
| | | 39 | | } |
| | 0 | 40 | | return $out |
| | | 41 | | } |
| | | 42 | | |
| | | 43 | | # Enumerable (but not string) → List<object> |
| | 0 | 44 | | if ($Value -is [System.Collections.IEnumerable] -and -not ($Value -is [string])) { |
| | 0 | 45 | | $list = New-Object System.Collections.Generic.List[object] |
| | 0 | 46 | | foreach ($item in $Value) { $list.Add((_NormalizeValueToDictionary $item ($depth + 1))) } |
| | 0 | 47 | | return $list |
| | | 48 | | } |
| | | 49 | | |
| | 0 | 50 | | return $Value # primitive / POCO |
| | | 51 | | } |