我有一个从CSV加载导入csv的数组。 数组$ s有$ s.Name和$ s.IPAddress。
当我运行作业时,我想过滤失败的作业,然后将它们与IP地址匹配的数组$ 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(未过滤),我有名称和IP地址
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
答案 0 :(得分:1)
有效的解决方案需要通过IP地址快速查找CSV导入的对象。
因此,我建议首先将导入的对象转换为由IP地址键入的哈希表:
# 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' }