Powershell 在填充 arrayList 时添加整数

Luc*_*man 2 powershell arraylist

我在 Powershell 中有一个函数,它用字典填充列表。

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
}
Run Code Online (Sandbox Code Playgroud)

它不是接收只返回 Hashtables 的 ArrayList,而是返回一个包含 Int32 和 Hashtable 的列表,其中每个哈希表元素都有一个 Int32:

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
Run Code Online (Sandbox Code Playgroud)

我不太确定为什么我的 ArrayList 中有这些整数。

Mat*_*sen 6

这里的问题是ArrayList.Add()返回添加新项目的索引。时return $control_list,表示索引位置的整数已写入管道

为方法调用添加前缀[void]以从 中删除输出Add()

[void]$control_list.Add($control_dict)
Run Code Online (Sandbox Code Playgroud)

或管道到Out-Null

$control_list.Add($control_dict) | Out-Null
Run Code Online (Sandbox Code Playgroud)