Hashtable转PSCustomObject异常:仅显示最后一条数据问题排查
PowerShell处理多组条目数据转换为PSCustomObject的修复方案
问题场景
处理clothes.txt文件时,文件包含多组colour、size、material、label条目,期望将每组数据转换为PSCustomObject并保留所有组的信息,但现有代码转换后仅显示最后一组数据。
文件内容
colour blue size large material velvet label red colour pink size small material cotton label blue colour green size medium material plastic label purple colour gold size medium material silk
原代码
Set-Location d:\temp Get-ChildItem .\clothes.txt | ForEach-Object { $hash = [ordered] @{} $_ | Select-String -Pattern '(colour|size|material) (.*)' | ForEach-Object { $hash[$_.Matches[0].Groups[1]] = $_.Matches[0].Groups[2] } [PSCustomObject]$hash }
原代码问题分析
哈希表的键具有唯一性,原代码中所有匹配到的同关键词(如colour)会不断覆盖哈希表中对应键的值,最终哈希表仅保留最后一组的条目,转换为PSCustomObject自然只显示最后一组数据。
修复方案
通过识别每组数据的起始标记(这里以colour作为每组的开头),每当开始新的一组时,先将上一组的哈希表转换为PSCustomObject存入结果集合,再重置哈希表收集新组数据。
修复后代码
Set-Location d:\temp # 初始化结果集合和当前条目哈希表 $itemCollection = @() $currentEntry = [ordered]@{} # 逐行读取文件内容处理 Get-Content .\clothes.txt | ForEach-Object { # 匹配关键词和对应值 if ($_ -match '(colour|size|material|label) (.*)') { $key = $matches[1] $value = $matches[2] # 遇到新的colour时,保存上一组数据并重置哈希表 if ($key -eq 'colour' -and $currentEntry.Count -gt 0) { $itemCollection += [PSCustomObject]$currentEntry $currentEntry = [ordered]@{} } # 将当前键值对存入哈希表 $currentEntry[$key] = $value } } # 保存最后一组未处理的数据 if ($currentEntry.Count -gt 0) { $itemCollection += [PSCustomObject]$currentEntry } # 输出所有结果 $itemCollection
预期输出
colour size material label ------ ---- -------- ----- blue large velvet red pink small cotton blue green medium plastic purple gold medium silk
内容的提问来源于stack exchange,提问作者Itchydon
相关产品推荐
相关产品推荐

