數組的元素可以使用索引尋址,第一個元素的索引為0,第i個元素的索引為i-1,最后一個元素的索引為Count-1,但是Powershell為了使用方便,直接可以將 -1 作為最后的一個元素的索引。
PS C:Powershell> $books="元素1","元素2","元素3"PS C:Powershell> $books[0]元素1PS C:Powershell> $books[1]元素2PS C:Powershell> $books[($book.Count-1)]元素3PS C:Powershell> $books[-1]元素3
從數組中選擇多個元素
PS C:Powershell> $result=lsPS C:Powershell> $result[0,3,5,12] Directory: C:PowershellMode LastWriteTime Length Name---- ------------- ------ ----d---- 2011/11/23 17:25 ABC-a--- 2011/11/24 20:04 26384 a.txt-a--- 2011/11/24 20:27 12060 alias.ps1-a--- 2011/11/24 17:37 7420 name.html
將數組逆序輸出
PS C:Powershell> $books="元素1","元素2","元素3"PS C:Powershell> $books[($books.Count)..0]元素3元素2元素1
給數組添加和刪除元素
因為Powershell數組在內存中是順序存儲的,所以數組的大小必須是確定的,這樣才方便分配存儲空間,所以給數組增加元素其實相當于創建一個新的數組,只不過之后會把原來的副本刪除。在當前數組追加元素可以使用“+=”操作符。
PS C:Powershell> $books="元素1","元素2","元素3"PS C:Powershell> $books+="元素4"PS C:Powershell> $books元素1元素2元素3元素4
要刪除第三個元素可是使用:
PS C:Powershell> $num=1..4PS C:Powershell> $num1234PS C:Powershell> $num=$num[0..1]+$num[3]PS C:Powershell> $num124
新聞熱點
疑難解答
圖片精選