PowerShell哈希表实战指南

哈希表基础操作

1
2
3
4
5
6
7
8
9
10
11
# 创建基础哈希表
$userProfile = @{
Name = '张三'
Department = 'IT'
LastLogin = (Get-Date).AddDays(-3)
}

# 属性访问的三种方式
Write-Host $userProfile['Name']
Write-Host $userProfile.Name
Write-Host $userProfile.Item('Department')

动态操作技巧

1
2
3
4
5
6
7
8
9
10
# 条件性添加属性
if (-not $userProfile.ContainsKey('Office')) {
$userProfile.Add('Office', 'Room 501')
}

# 带类型约束的哈希表
[ordered][System.Collections.Hashtable]$configTable = @{
LogLevel = 'Debug'
MaxRetry = 3
}

实际应用场景

1
2
3
4
5
6
7
8
9
10
# 配置文件转换示例
$rawConfig = Get-Content appsettings.json | ConvertFrom-Json
$configTable = @{
Environment = $rawConfig.Env
Features = $rawConfig.Features -join ';'
Timeout = [timespan]::FromMinutes($rawConfig.WaitTime)
}

# 快速对象比较
$diff = Compare-Object $oldTable.GetEnumerator() $newTable.GetEnumerator() -Property Name,Value

PowerShell 哈希表实战技巧

基础操作演示

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 创建带类型约束的哈希表
$userProfile = [ordered]@{
Name = '张三'
Age = 28
Role = '管理员'
}

# 动态参数生成
function New-Service {
param($ServiceParams)
Start-Process -FilePath 'notepad.exe' @ServiceParams
}

$params = @{
WindowStyle = 'Maximized'
PassThru = $true
}
New-Service -ServiceParams $params

数据筛选应用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 构建商品库存系统
$inventory = @{
'笔记本' = @{ Price=5999; Stock=15 }
'手机' = @{ Price=3999; Stock=30 }
'耳机' = @{ Price=299; Stock=100 }
}

# 实时库存查询
$inventory.Keys | Where-Object {
$inventory[$_].Price -lt 5000 -and
$inventory[$_].Stock -gt 20
} | ForEach-Object {
[PSCustomObject]@{
商品 = $_
价格 = $inventory[$_].Price
库存 = $inventory[$_].Stock
}
}

最佳实践

  1. 使用[ordered]创建有序字典
  2. 通过嵌套哈希表构建层级数据
  3. 用ConvertTo-Json实现数据序列化
  4. 结合Splatting传递动态参数
  5. 使用ContainsKey方法进行安全校验