NKF
NKF

Reputation: 63

Powershell how to return multiple properties from array

I have an array that i load from CSV with import csv. The array $s has $s.Name and $s.IPAddress.

When I m running jobs I want to filter the failed jobs and then compare them with the array $s where the IPAddress matches, finally I want to show the values in $s with $s.Name and $s.IPAddress...

So far I can only get the IPAddress because after I apply the filter Where I1m left with only that property.

How can I get the correspondent array value for Name and IPAddress where I find the match?

Here's the code as you see only returns IP address, but I want the correspondent Name that exists in $s as well

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

If I do $s(not filtered), I have Name and 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

So the goal with this

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

is to get the output like this

Server101   192.1.8.149
Server104   192.1.8.152
Server107   192.1.8.155

Upvotes: 1

Views: 790

Answers (1)

mklement0
mklement0

Reputation: 437933

An efficient solution requires fast lookups of your CSV-imported objects by IP address.

Therefore, I recommend converting the imported objects to a hashtable keyed by IP address first:

# 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' }

Upvotes: 1

Related Questions