【问题标题】:Powershell how to return multiple properties from arrayPowershell如何从数组中返回多个属性
【发布时间】:2017-07-26 11:56:19
【问题描述】:

我有一个数组,我使用导入 csv 从 CSV 加载。 数组 $s 有 $s.Name 和 $s.IPAddress。

当我运行作业时,我想过滤失败的作业,然后将它们与 IPAddress 匹配的数组 $s 进行比较,最后我想用 $s.Name 和 $s.IPAddress 显示 $s 中的值。 ..

到目前为止,我只能获取 IPAddress,因为在我应用过滤器之后,I1m 只剩下该属性。

如何在我找到匹配项的地方获取 Name 和 IPAddress 的对应数组值?

这是您看到的代码,仅返回 IP 地址,但我也想要 $s 中存在的对应名称

PS C:\> $j.ChildJobs | ?{$_.State -eq 'Failed'} | %{$s.IPAddress -eq $_.Location}
192.1.8.149
192.1.8.152
192.1.8.155

如果我做 $s(未过滤),我有名称和 IPAddress

PS C:\> $s

Name        IPAddress
----        ---------
Server100   192.1.8.148
Server101   192.1.8.149
Server102   192.1.8.150
Server103   192.1.8.151
Server104   192.1.8.152
Server105   192.1.8.153
Server106   192.1.8.154
Server107   192.1.8.155

所以这个目标

PS C:\> $j.ChildJobs | ?{$_.State -eq 'Failed'} | %{$s.IPAddress -eq $_.Location}

就是得到这样的输出

Server101   192.1.8.149
Server104   192.1.8.152
Server107   192.1.8.155

【问题讨论】:

  • 输出的格式有什么影响?
  • $s.IPAddress -eq $_.Location -> $l=$_.Location;$s |?{$.IPAddress -eq $l}
  • 所以我可以识别失败的 IPAddress 的名称,这对于我想要实现的目标来说更容易
  • 你能粘贴完整的命令和你的建议吗?
  • 好的,谢谢

标签: powershell


【解决方案1】:

高效的解决方案需要通过 IP 地址快速查找 CSV 导入的对象。

因此,我建议先将导入的对象转换为以 IP 地址为键的 hashtable

# Convert the CSV-imported custom objects to a hashtable that maps
# IP addresses to names.
$ht = @{}
$s | % { $ht[$_.IPAddress] = $_.Name }

# Process the jobs and look up the name corresponding to a job's
# IP address in the hashtable, using Select-Object with calculated properties.
$j.ChildJobs | ? State -eq 'Failed' |
  Select-Object @{ l='Name'; e={ $ht[$_.Location] } }, @{ l='IPAddress'; e='Location' }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-01
    • 1970-01-01
    • 2014-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多