茫茫網海中的冷日 - 對這文章發表回應
茫茫網海中的冷日
         
茫茫網海中的冷日
發生過的事,不可能遺忘,只是想不起來而已!
 恭喜您是本站第 1729932 位訪客!  登入  | 註冊
主選單

Google 自訂搜尋

Goole 廣告

隨機相片
FF18_Paintcar_00062.jpg

授權條款

使用者登入
使用者名稱:

密碼:


忘了密碼?

現在就註冊!

對這文章發表回應

發表限制: 非會員 可以發表

發表者: 冷日 發表時間: 2016/2/24 10:36:40

Adding and Removing Items from a PowerShell Array

Adding and removing Items from a PowerShell array is a topic which can lead to some confusion, so here are a few tips for you.

Create an array and we will note the type System.Array:



$Fruits = "Apple","Pear","Banana","Orange"
$Fruits.GetType()

However, if we try to Add or Remove items to the array we get errors that the “Collection was of a fixed size”



$Fruits.Add("Kiwi")
$Fruits.Remove("Apple")
$Fruits.IsFixedSize

We can see that the array we originally created is of a fixed size. The MSDN page for the ISFixedSize Property helps to explain this. Note it supports the modification of existing elements, but not the addition or removal of others.

One way to deal with this is to use a
System.Collections.ArrayList instead



[System.Collections.ArrayList]$ArrayList = $Fruits
$ArrayList.GetType()

Now if we try the previous add and remove methods we are successful:



$ArrayList.Add("Kiwi")
$ArrayList
$ArrayList.Remove("Apple")
$ArrayList

Alternatively, if we had stuck with the original Array object we could do the following to ‘add’ an item to it. (Actually it creates a new array with an additional item)



$New = $Fruits += "Kiwi"
$New
$New.GetType()

However, we can’t remove items in this way:



$New2 = $Fruits -= "Apple"

We could instead do this:



$New3 = $Fruits -ne "Apple"
$New3

 

Update: Thanks to Rob Campbell for pointing out another way to do this.

Taking your initial array you can convert it to a System.Collections.ObjectModel.Collection`1 like this, which may be easier to remember than using the full type name of either a collection or array list:



$Collection = {$Fruits}.Invoke()
$Collection
$Collection.GetType()

Now we can add and remove items using the Add and Remove methods:



$Collection.Add("Melon")
$Collection
$Collection.Remove("Apple")
$Collection


原文出處: Adding and Removing Items from a PowerShell Array | Jonathan Medd's Blog
內容圖示
url email imgsrc image code quote
樣本
bold italic underline linethrough   












 [詳情...]
validation picture

注意事項:
預覽不需輸入認證碼,僅真正發送文章時才會檢查驗證碼。
認證碼有效期10分鐘,若輸入資料超過10分鐘,請您備份內容後,重新整理本頁並貼回您的內容,再輸入驗證碼送出。

選項

Powered by XOOPS 2.0 © 2001-2008 The XOOPS Project|