2014-07-23 51 views
1

Powershell「添加成員」命令非常有用。我用它來爲自定義對象添加屬性。有時我將一個成員設置爲一個數組來容納多個對象。是否有可能添加一個ArrayList作爲一個自定義對象的成員?Powershell添加成員。添加一個ArrayList成員?

想象的文章列表具有屬性「指標」,「標題」和「關鍵詞」。在PowerShell中,你可以把這個代碼在一個循環:

for($i = 0; $i -lt 100; $i++) { 
    $a = new-object -TypeName PSObject 
    $a | Add-Member -MemberType NoteProperty -Name index -Value $i 
    $a | Add-Member -MemberType NoteProperty -Name title -Value "Article $i" 
    $a | Add-Member -MemberType NoteProperty -Name keywords -Value @() 
    $articles += $a 
} 

你會落得一個數組,$的文章,文章的對象,每一個成員的索引,標題和關鍵字。此外,關鍵詞成員是一個數組,可以有多個條目:

$articles[2].keywords += "Stack Exchange", "Powershell", "ArrayLists" 
$articles[2].keywords[2] 
Powershell 

這符合我的大部分需求,但我就是不喜歡處理數組。的ArrayList只是比較容易的工作,如果僅僅是因爲

$arrayList1.remove("value") 

是如此比

$array1 = $array1 |? {$_ new "value"} 

更直觀是否有與添加會員的方式來添加一個ArrayList成爲會員?或者我堅持數組?如果Powershell不支持snatively,我可以彈出一些C#代碼來創建一個ArrayList作爲成員的新類嗎?

回答

7
$arr = @("one","two","three") 
$arr.GetType() 

IsPublic IsSerial Name          BaseType                      
-------- -------- ----          --------                      
True  True  Object[]         System.Array 

$a = new-object -TypeName PSObject 
[System.Collections.ArrayList]$arrList=$arr 
$a | Add-Member -MemberType NoteProperty -Name ArrayList -value $arrlist 

$a.ArrayList 

one 
two 
three 

$a.ArrayList.remove("one") 
$a.ArrayList 

two 
three 

到空白的ArrayList添加到您的自定義對象只需使用

$a | Add-Member -MemberType NoteProperty -Name ArrayList -value (New-object System.Collections.Arraylist) 
+0

哦。所以...在一個單獨的變量中創建對象(上例中的$ arrList)。然後將該變量設置爲Add-Member中的NoteProperty的值。我有這個權利嗎? – Bagheera

+0

遵循這個邏輯...我可以添加任何「新對象」,我想作爲另一個對象的成員? – Bagheera

+0

是的,對於我知道的自定義對象,可以添加哪些對象作爲NoteProperty沒有限制。不,你不必創建一個單獨的變量,對不起,我沒有說清楚,這只是一個例子。更新.. – Cole9350

3

我覺得這一切加入會員的東西是隻數據混亂。在PowerShell中3,你可以使物體從一個哈希表,並使用一個小東西,我從一個blog學習瞭如何使用調用得到一個集合類型的對象:

$myObject = [PSCustomObject]@{ 
     index = $idx; 
     title = $title; 
     keywords = {@()}.Invoke() 
    } 

$myObject.keywords.Add("foo") 
$myObject.keywords.Add("bar") 

Write-Host "Original" 
$myObject.keywords 
Write-Host 

Write-Host "New:" 
[void]$myObject.keywords.Remove("foo") 
$myObject.keywords 
Write-Host 

Original 
foo 
bar 

New: 
bar