2015-07-13 34 views
1

我在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 
} 

不是接收僅返回哈希表,它返回它具有的Int32和Hashtable,那裏是一個Int32在它的每個哈希表元素的列表中的ArrayList:

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 

我不是真的確定爲什麼我的ArrayList中有這些整數。

回答

2

這裏的問題是,ArrayList.Add()返回添加新項目的索引。當你return $control_list,代表索引位置的整數已經被寫入到管道

前綴與[void]方法調用從Add()去除輸出:

[void]$control_list.Add($control_dict) 

或者管Out-Null

$control_list.Add($control_dict) | Out-Null 
0

System.Collections.ArrayList::Add()添加對象,而不是鍵值對,所以當你這樣做時$control_dict.Add($line_split[0],$line_split[1])你要添加兩個對象,一個整數和一個散列表。如果你想使用整數作爲鍵,而不是,你應該使用一個哈希表屬性賦值,就像這樣:

$control_dict.($line_split[0]) = $line_split[1] 

您需要的$line_split[0]包裝成支架,使正確的密鑰將被添加,否則值查詢會是$control_dict.$line_split它是有效的,因爲散列表接受對象作爲鍵,空作爲從未分配,然後得到[0]超出空值將淨你一個例外。

+0

除$ control_dict是散列表類型?剛剛嘗試過你的方法,它仍然產生相同的結果 –

1

爲什麼你不只是聲明一個空數組,然後使用「+ =」而不是Add()?

$control_list = @() 
$hash = [PSCustomObject]@{} 
$control_list += $hash 

此外,爲什麼你解析節點爲文本?