|
1 | | -function Remove-EmptyArrays { |
2 | | - <# |
3 | | - .SYNOPSIS |
4 | | - Recursively removes empty arrays and null properties from objects |
5 | | - .DESCRIPTION |
6 | | - This function recursively traverses an object (Array, Hashtable, or PSCustomObject) and removes: |
7 | | - - Empty arrays |
8 | | - - Null properties |
9 | | - The function modifies the object in place. |
10 | | - .PARAMETER Object |
11 | | - The object to process (can be Array, Hashtable, or PSCustomObject) |
12 | | - .FUNCTIONALITY |
13 | | - Internal |
14 | | - .EXAMPLE |
15 | | - $obj = @{ items = @(); name = "test"; value = $null } |
16 | | - Remove-EmptyArrays -Object $obj |
17 | | - .EXAMPLE |
18 | | - $obj = [PSCustomObject]@{ items = @(); name = "test" } |
19 | | - Remove-EmptyArrays -Object $obj |
20 | | - #> |
21 | | - [CmdletBinding()] |
22 | | - param( |
23 | | - [Parameter(Mandatory = $true)] |
24 | | - [object]$Object |
25 | | - ) |
26 | | - |
| 1 | +function Remove-EmptyArrays ($Object) { |
27 | 2 | if ($Object -is [Array]) { |
28 | | - foreach ($Item in $Object) { |
29 | | - Remove-EmptyArrays -Object $Item |
30 | | - } |
| 3 | + foreach ($Item in $Object) { Remove-EmptyArrays $Item } |
31 | 4 | } elseif ($Object -is [HashTable]) { |
32 | 5 | foreach ($Key in @($Object.get_Keys())) { |
33 | 6 | if ($Object[$Key] -is [Array] -and $Object[$Key].get_Count() -eq 0) { |
34 | 7 | $Object.Remove($Key) |
35 | | - } else { |
36 | | - Remove-EmptyArrays -Object $Object[$Key] |
37 | | - } |
| 8 | + } else { Remove-EmptyArrays $Object[$Key] } |
38 | 9 | } |
39 | 10 | } elseif ($Object -is [PSCustomObject]) { |
40 | 11 | foreach ($Name in @($Object.PSObject.Properties.Name)) { |
41 | 12 | if ($Object.$Name -is [Array] -and $Object.$Name.get_Count() -eq 0) { |
42 | 13 | $Object.PSObject.Properties.Remove($Name) |
43 | 14 | } elseif ($null -eq $Object.$Name) { |
44 | 15 | $Object.PSObject.Properties.Remove($Name) |
45 | | - } else { |
46 | | - Remove-EmptyArrays -Object $Object.$Name |
47 | | - } |
| 16 | + } else { Remove-EmptyArrays $Object.$Name } |
48 | 17 | } |
49 | 18 | } |
50 | 19 | } |
0 commit comments