Reputation: 13
If I import a csv of computer names $computers that looks like this
Host
----
computer5
Computer20
Computer1
and import another csv of data $data that looks like this
Host OS HD Capacity Owner
---- -- -- ------ -----
Computer20 Windows7 C 80 Becky
Computer1 Windows10 C 80 Tom
Computer1 Windows10 D 100 Tom
computer5 Windows8 C 100 sara
computer5 Windows8 D 1000 sara
computer5 Windows8 E 1000 sara
Im trying to do this
foreach ($pc in $computers){
$hostname = $pc.host
foreach ($entry in $data | where {$enty.host -eq $hostname})
{write-host "$entry.Owner"}
}
The foreach statement isn't finding any matches. How can I fix this? Im trying to do more than just write the owner name but, this is the basic premise
Thanks! Steve
Upvotes: 0
Views: 1129
Reputation: 27418
Here's another way to do it, using an array $computers.host
on the left side of the -eq operator:
$computers = 'Host
computer5
Computer20
Computer1' | convertfrom-csv
$data = 'Host,OS,HD,Capacity,Owner
Computer20,Windows7,C,80,Becky
Computer1,Windows10,C,80,Tom
Computer1,Windows10,D,100,Tom
computer5,Windows8,C,100,sara
computer5,Windows8,D,1000,sara
computer5,Windows8,E,1000,sara' | convertfrom-csv
$data | where { $computers.host -eq $_.host } | ft
Host OS HD Capacity Owner
---- -- -- -------- -----
Computer20 Windows7 C 80 Becky
Computer1 Windows10 C 80 Tom
Computer1 Windows10 D 100 Tom
computer5 Windows8 C 100 sara
computer5 Windows8 D 1000 sara
computer5 Windows8 E 1000 sara
Or
$data | where host -in $computers.host
Or
foreach ( $entry in $data | where host -in $computers.host | foreach owner ) {
$entry }
Becky
Tom
Tom
sara
sara
sara
Assuming $entry is spelled correctly, this syntax just happens not to work.
The expression $data | where {$entry.host -eq $hostname}
just doesn't make sense by itself. Good question though. You can indeed use a pipeline in the parens after foreach.
foreach ($pc in $computers){
$hostname = $pc.host
foreach ($entry in $data | where {write-host "entry is $entry";
$entry.host -eq $hostname}){
write-host "$entry.Owner"
}
}
entry is
entry is
entry is
entry is
entry is
entry is
entry is
entry is
entry is
entry is
entry is
entry is
entry is
entry is
entry is
entry is
entry is
entry is
Upvotes: 0
Reputation: 174435
Replace $enty
with $_
inside the Where-Object
filter block:
foreach ($entry in $data |Where-Object {$_.host -eq $hostname}){
Write-Host $entry.Owner
}
Upvotes: 2