Question:
I have a function in Powershell which populates a list with dictionaries.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
Function Process-XML-Audit-File-To-Controls-List($nodelist){ #Keep an array list to track the different controls $control_list = New-Object System.Collections.ArrayList foreach($var in $nodelist) { $lines = [string]($var.InnerText) -split '[\r\n]' $control_dict = @{} foreach($line in $lines){ $line_split = $line.Trim() -split ':',2 if($line_split.Length -eq 2){ $control_dict.Add($line_split[0],$line_split[1]) } } $control_list.Add($control_dict) } return $control_list } |
Instead of receiving an ArrayList which returns only Hashtables it returns a list which has Int32 and Hashtable, where there is an Int32 in it for each hashtable element:
1 2 3 4 5 6 7 |
True True Int32 System.ValueType True True Int32 System.ValueType True True Int32 System.ValueType True True Hashtable System.Object True True Hashtable System.Object True True Hashtable System.Object |
I’m not really sure why I have those integers in my ArrayList.
Answer:
The problem here is that ArrayList.Add()
returns the index at which the new item was added. When you return $control_list
, the integers representing the index locations have already been written to the pipeline
Prefix the method call with [void]
to remove the output from Add()
:
1 2 |
[void]$control_list.Add($control_dict) |
Or pipe to
Out-Null
:
1 2 |
$control_list.Add($control_dict) | Out-Null |