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

Google 自訂搜尋

Goole 廣告

隨機相片
IMG_60D_00343.jpg

授權條款

使用者登入
使用者名稱:

密碼:


忘了密碼?

現在就註冊!

微軟帝國 : [轉貼]Adding and Removing Items from a PowerShell Array

發表者 討論內容
冷日
(冷日)
Webmaster
  • 註冊日: 2008/2/19
  • 來自:
  • 發表數: 15773
[轉貼]Adding and Removing Items from a PowerShell Array

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
前一個主題 | 下一個主題 | | | |

討論串




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