PowerShell 哈希表

哈希表是一种键值对集合,适合保存配置、参数映射和快速查找数据。在 PowerShell 中,哈希表使用 @{} 创建。

创建哈希表

$user = @{
  Name = "Alice"
  Age = 30
  Role = "Admin"
}

访问值:

$user["Name"]
$user.Name

添加和修改元素

$user["Email"] = "alice@example.com"
$user.Role = "Owner"

判断键是否存在:

if ($user.ContainsKey("Email")) {
  "Email exists"
}

删除元素

$user.Remove("Age")

遍历哈希表

foreach ($item in $user.GetEnumerator()) {
  "{0}: {1}" -f $item.Key, $item.Value
}

有序哈希表

普通哈希表不保证输出顺序。如果需要保留插入顺序,可以使用 [ordered]

$config = [ordered]@{
  Host = "localhost"
  Port = 8080
  Debug = $true
}

作为命令参数

哈希表经常配合参数展开使用。

$params = @{
  Path = "."
  Filter = "*.md"
  Recurse = $true
}

Get-ChildItem @params

这种写法可以让长命令更清晰,也便于复用参数。

嵌套哈希表

$settings = @{
  Database = @{
    Host = "localhost"
    Port = 5432
  }
  Logging = @{
    Level = "Information"
  }
}

$settings.Database.Host

转换为 JSON

哈希表常用于生成 JSON 配置。

$settings | ConvertTo-Json -Depth 3

小结

哈希表适合表示结构化配置和键值映射。常用操作包括创建、读取、修改、删除、遍历,以及配合 @params 展开命令参数。