欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Windows Powershell 访问数组

程序员文章站 2022-05-07 17:02:22
数组的元素可以使用索引寻址,第一个元素的索引为0,第i个元素的索引为i-1,最后一个元素的索引为count-1,但是powershell为了使用方便,直接可以将 -1 作为...

数组的元素可以使用索引寻址,第一个元素的索引为0,第i个元素的索引为i-1,最后一个元素的索引为count-1,但是powershell为了使用方便,直接可以将 -1 作为最后的一个元素的索引。

ps c:powershell> $books="元素1","元素2","元素3"
ps c:powershell> $books[0]
元素1
ps c:powershell> $books[1]
元素2
ps c:powershell> $books[($book.count-1)]
元素3
ps c:powershell> $books[-1]
元素3


从数组中选择多个元素

ps c:powershell> $result=ls
ps c:powershell> $result[0,3,5,12]
  directory: c:powershell

mode        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..4
ps c:powershell> $num
1
2
3
4
ps c:powershell> $num=$num[0..1]+$num[3]
ps c:powershell> $num
1
2
4