PowerShell对象Action属性值按哈希表替换异常问题排查
问题描述
我有一个存储在$array中的PSObj,结构如下:
ComputerName : MyComputer Time : 08/11/2022 13:57:53 DetectionFile : MyBadFile.exe ThreatName : WS.Reputation.1 Action : 12
已定义哈希表$ActionId用来将Action ID替换为对应描述:
$ActionId = @{ 0 = 'Unknown' 1 = 'Blocked' 2 = 'Allowed' 3 = 'No Action' 4 = 'Logged' 5 = 'Command Script Run' 6 = 'Corrected' 7 = 'Partially Corrected' 8 = 'Uncorrected' 10 = 'Delayed Requires reboot to finish the operation.' 11 = 'Deleted' 12 = 'Quarantined' 13 = 'Restored' 14 = 'Detected' 15 = 'Exonerated No longer suspicious (re-scored).' 16 = 'Tagged Marked with extended attributes.' }
编写了如下代码遍历数组尝试替换,但执行后Action属性变为null且无报错,求正确语法:
# parse array foreach ($Item in $array) { # parse possible values foreach ($value in $ActionId) { if ($value -eq $item.Action) { $Item.Action = $ActionId[$value] $Item.Action } } }
问题原因
直接遍历$ActionId得到的是哈希表的值(如Unknown、Blocked),而非对应的ID键(0、1等)。拿这些字符串值和$Item.Action的数字ID做比较,永远不会匹配,因此赋值逻辑从未执行;若代码存在意外覆盖逻辑,就会导致Action变为null。
正确解法
解法1:直接通过哈希表键取值(最简洁高效)
无需嵌套循环,直接利用哈希表的键查找特性获取对应描述,同时可添加键存在性校验避免无匹配时返回null:
foreach ($Item in $array) { if ($ActionId.ContainsKey($Item.Action)) { $Item.Action = $ActionId[$Item.Action] } else { # 可选:处理未定义的Action ID,比如保留原ID或标记 $Item.Action = "Unknown Action: $($Item.Action)" } }
解法2:遍历哈希表的键集合
若需遍历哈希表,需遍历其键集合$ActionId.Keys,匹配键与Action ID:
foreach ($Item in $array) { foreach ($key in $ActionId.Keys) { if ($key -eq $Item.Action) { $Item.Action = $ActionId[$key] break # 找到匹配后跳出循环,提升效率 } } }
内容的提问来源于stack exchange,提问作者Douda
相关产品推荐
相关产品推荐

