PowerShell 技能连载 - 集合操作方法

基础集合操作

1
2
3
4
5
6
7
8
9
10
11
# 创建强类型集合
[System.Collections.Generic.List[string]]$list = @()
$list.AddRange(@('Server01','Server02'))

# 哈希表快速查询
$configTable = @{
Timeout = 30
Retries = 3
LogPath = 'C:\Logs'
}
$configTable.ContainsKey('Timeout')

应用场景

  1. 数据过滤
1
Get-Process | Where-Object {$_.CPU -gt 100 -and $_.Name -notmatch '^svchost$'}
  1. 批量重命名
1
2
3
4
5
$files = Get-ChildItem *.log
$files | ForEach-Object {
$newName = $_.Name -replace '_old','_new'
Rename-Item $_ $newName
}

最佳实践

  1. 使用泛型集合提升性能
1
2
$queue = [System.Collections.Queue]::new()
1..10000 | ForEach-Object {$queue.Enqueue($_)}
  1. 利用管道优化内存使用
1
2
# 流式处理大文件
Get-Content huge.log | Where-Object {$_ -match 'ERROR'} | Export-Csv errors.csv
  1. 嵌套集合处理
1
2
3
4
5
6
$serverData = @(
[PSCustomObject]@{Name='WEB01'; Role='Frontend'}
[PSCustomObject]@{Name='DB01'; Role='Database'}
)

$serverData.Where({$_.Role -eq 'Frontend'}).ForEach({$_.Name})
作者

Victor Woo

发布于

2025-03-13

更新于

2025-03-13

许可协议

PowerShell 技术 QQ 群