gpt4 book ai didi

powershell - 根据列表替换 PSObj 属性值

转载 作者:行者123 更新时间:2023-12-02 15:44:41 26 4
gpt4 key购买 nike

我有以下 PSObj,其中一些属性存储在 $array 中:

ComputerName      : MyComputer
Time : 08/11/2022 13:57:53
DetectionFile : MyBadFile.exe
ThreatName : WS.Reputation.1
Action : 12

我正在尝试用相应的描述替换操作 ID 号。我有一个哈希表,其中包含操作 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.'
}

我正在尝试解析此数组的每个项目,以及原因 ID 的每个值以用原因字符串替换 ID

    # parse array
foreach ($Item in $array) {
# parse possible values
foreach ($value in $ActionId) {
if ($value -eq $item.Action) {
$Item.Action = $ActionId[$value]
$Item.Action
}
}

根据我的理解,我在这里缺少正确的语法

$Item.Action = $ActionId[$value]

我没有收到任何错误,但是从调试器中,我用上面的 $null 替换了 action 属性...

最佳答案

直接的解决方法是循环 keys (.Keys) 你的 $ActionId hashtable :

foreach ($Item in $array) {
# parse possible values
foreach ($value in $ActionId.Keys) {
if ($value -eq $item.Action) {
$Item.Action = $ActionId[$value]
$Item.Action # diagnostic output
}
}
}

注意:

  • 为避免混淆,考虑将 $value 重命名为 $key

  • 通常,请注意哈希表在管道/PowerShell 中的循环构造中枚举

    • 也就是说,foreach ($value in $ActionId) ... 实际上并不遍历哈希表的条目,与 $value = $ActionID 相同)

    • 如果您想枚举哈希表的条目 - 作为类型为 System.RuntimeType 的键值对 - 您需要使用 .GetEnumerator() 方法;但是,在您的情况下,枚举 就足够了。


但是,更简单、更有效的解决方案是测试$Item.Action 值是否作为键存在于您的哈希表中,使用后者的 .Contains() 方法:<支持>[1]

foreach ($Item in $array) {
if ($ActionId.Contains($Item.Action)) {
$Item.Action = $ActionId[$Item.Action]
$Item.Action # diagnostic output
}
}

您可以按如下方式进一步简化,尽管它在概念上有点晦涩:

foreach ($Item in $array) {
if ($null -ne ($value = $ActionId[$Item.Action])) {
$Item.Action = $value
$Item.Action # diagnostic output
}
}
  • = 只是 PowerShell 的赋值运算符;对于相等/不相等比较-eq/-ne 是必需的。

  • 此处,确实执行了对 $value 的赋值,赋值 然后充当 -ne 的 RHS > 操作;换句话说:您可以在 PowerShell 中使用赋值作为表达式

  • 如果哈希表 $ActionId 没有没有值为 $Item.Action 的键,$ActionId[$Item. Action] 安静地返回 $null


最后 - 仅在 PowerShell (Core) 7+ 中 - 一个更简洁(虽然不一定更快)的解决方案是可能的,使用 ??null-coalescing operator :

foreach ($Item in $array) {
$Item.Action = $ActionId[$Item.Action] ?? $Item.Action
$Item.Action # diagnostic output
}

也就是说,$ActionId[$Item.Action] 的值仅在 不是 $null 时使用;否则,使用 $Item.Action,即当前值(这实际上是一个空操作)。


[1] .ContainsKey() 也有效,虽然这个名称在概念上比 .Contains() 更清晰,但遗憾的是它不受 PowerShell 的支持[ordered] 哈希表 ( System.Collections.Specialized.OrderedDictionary ),一般来说,其他字典(类哈希表类型)不支持,因为 System.Collections.IDictionary 接口(interface)只有 .Contains()

关于powershell - 根据列表替换 PSObj 属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74645516/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com