PowerShell 技能连载 - 集合操作方法
基础集合操作
1 | # 创建强类型集合 |
应用场景
数据过滤:
1
Get-Process | Where-Object {$_.CPU -gt 100 -and $_.Name -notmatch '^svchost$'}
批量重命名:
1
2
3
4
5$files = Get-ChildItem *.log
$files | ForEach-Object {
$newName = $_.Name -replace '_old','_new'
Rename-Item $_ $newName
}
最佳实践
使用泛型集合提升性能
1
2$queue = [System.Collections.Queue]::new()
1..10000 | ForEach-Object {$queue.Enqueue($_)}利用管道优化内存使用
1
2# 流式处理大文件
Get-Content huge.log | Where-Object {$_ -match 'ERROR'} | Export-Csv errors.csv嵌套集合处理
1
2
3
4
5
6$serverData = @(
[PSCustomObject]@{Name='WEB01'; Role='Frontend'}
[PSCustomObject]@{Name='DB01'; Role='Database'}
)
$serverData.Where({$_.Role -eq 'Frontend'}).ForEach({$_.Name})
PowerShell 技能连载 - 集合操作方法
http://blog.vichamp.com/2025/03/13/powershell-collection-operations/