约 2006 字

约 10 分钟

#哈希表

#简介

哈希表(hashtable)以键值对的形式保存数据,适合按名称快速查找。PowerShell 使用 @{} 创建哈希表,键和值之间用 = 分隔。

#创建哈希表

> $person = @{
>>     Name = "Tom"
>>     Age  = 18
>>     City = "Beijing"
>> }

键也可以是字符串字面量:

> $config = @{
>>     "log-level" = "info"
>>     "max-size"  = 100
>> }

#访问元素

可以使用方括号或点号访问:

> $person["Name"]
Tom
> $person.Name
Tom
> $person["Age"]
18

当键包含空格或特殊字符时,必须使用方括号:

> $config["log-level"]
info

访问不存在的键会返回 $null。

#增删改

> $person["Age"] = 19
> $person.Email = "[email protected]"
> $person.Remove("City")
> $person
Name  Age Email
----  --- -----
Tom    19 [email protected]
  • 使用 = 添加或修改键值。
  • 使用 Remove() 删除键。
  • 使用 ContainsKey() 判断键是否存在:
> $person.ContainsKey("Email")
True

#遍历哈希表

直接遍历哈希表得到的是键值对对象,通常配合 GetEnumerator() 使用:

> foreach ($entry in $person.GetEnumerator()) {
>>     "{0} = {1}" -f $entry.Key, $entry.Value
>> }
Name = Tom
Age = 19
Email = [email protected]

也可以只遍历键或值:

> $person.Keys
> $person.Values

#有序哈希表

普通哈希表的顺序不保证稳定。需要保持插入顺序时使用 [ordered]:

> $ordered = [ordered]@{
>>     First  = 1
>>     Second = 2
>>     Third  = 3
>> }
> $ordered.Keys
First
Second
Third

[ordered] 实际上是 System.Collections.Specialized.OrderedDictionary 的简写。

#Splatting

splatting 把哈希表的键值对作为命令参数传入,使长命令更易读:

$params = @{
    Path        = "./data"
    Filter      = "*.txt"
    Recurse     = $true
    ErrorAction = "Stop"
}

Get-ChildItem @params

调用时使用 @params 而不是 $params。键名对应参数名,键值对应参数值。

#推荐阅读

更新: 2026/11/2

作者: planc

创建: 2026/11/2