约 2144 字

约 11 分钟

#数组与集合

#简介

数组用于按顺序保存一组值。PowerShell 的数组可以包含不同类型元素,并且支持索引、切片、遍历等操作。对于需要频繁增删元素的场景,还可以使用 .NET 提供的集合类型。

#创建数组

使用 @() 创建数组,元素之间用逗号分隔:

> $items = @("a", "b", "c")
> $numbers = @(1, 2, 3)
> $mixed = @("text", 42, $true)

逗号本身也能创建数组:

> $items = "a", "b", "c"
> $items.GetType().Name
Object[]

空数组写作 @()。

#索引与切片

数组索引从 0 开始,使用方括号访问:

> $items = @("a", "b", "c", "d")
> $items[0]
a
> $items[-1]
d
> $items[1..2]
b
c
  • -1 表示最后一个元素。
  • 1..2 是范围表达式,返回切片。
  • 索引越界不会报错,而是返回 $null。

#数组长度

使用 Count 或 Length 获取元素个数:

> $items.Count
4
> $items.Length
4

#添加元素

数组长度固定,使用 += 实际上会创建一个新数组:

> $items += "e"
> $items.Count
5

#遍历

使用 foreach 语句遍历数组:

> foreach ($item in $items) {
>>     Write-Output "Item: $item"
>> }
Item: a
Item: b
Item: c
Item: d
Item: e

也可以使用 ForEach-Object 通过管道处理:

> $items | ForEach-Object { $_.ToUpper() }

两者的区别是:foreach 是语句,一次处理整个集合;ForEach-Object 是命令,逐个处理管道传入的对象。

#集合类型

#ArrayList

System.Collections.ArrayList 支持动态增删:

> $list = [System.Collections.ArrayList]::new()
> $null = $list.Add("a")
> $null = $list.Add("b")
> $list.Remove("a")
> $list.Count
1

Add() 会返回新元素的索引,通常用 $null = 抑制输出。

#泛型 List

System.Collections.Generic.List[object] 是更现代的选择:

> $list = [System.Collections.Generic.List[object]]::new()
> $list.Add("a")
> $list.Add(42)
> $list
a
42

将类型参数写成具体类型(例如 [string])可以获得更好的类型约束。

#管道输出成为数组

当命令产生多个结果时,PowerShell 会把它们作为数组返回:

> $files = Get-ChildItem
> $files -is [array]
True
> $files.Count

即使只有一个结果,也可以使用 @() 强制转换为数组:

> $one = @(Get-ChildItem -Filter *.ps1)
> $one.Count

#推荐阅读

更新: 2026/11/2

作者: planc

创建: 2026/11/2