See if this works better:
$old = Import-Excel -path C:\junk\old.xlsx
$new = Import-Excel -Path C:\junk\New.xlsx
$arr = @()
$i = 0
foreach ($vm1 in $old) {
$found = $false
$i++
foreach ($vm2 in $new) {
if ($vm1.'dns' -eq $vm2.'dns' -and $vm1.'ip' -eq $vm2.'ip' ) {
$status = " DNS and IP match"
$vm1_dns = $vm1.dns
$vm1_ip = $vm1.ip
$vm2_dns = $vm2.dns
$vm2_ip = $vm2.ip
$found = $true
$arr += [PSCustomObject]@{
Sno = $i
Status = $Status
'Old List DNS' = $vm1_dns
'Old List IP' = $vm1_ip
Empty = '<<->>'
'New List DNS' = $vm2_dns
'New List IP' = $vm2_ip
}
}
elseif ($vm1.'ip' -eq $vm2.'ip') {
$status = " IP match"
$vm1_dns = $vm1.dns
$vm1_ip = $vm1.ip
$vm2_dns = $vm2.dns
$vm2_ip = $vm2.ip
$found = $true
$arr += [PSCustomObject]@{
Sno = $i
Status = $Status
'Old List DNS' = $vm1_dns
'Old List IP' = $vm1_ip
Empty = '<<->>'
'New List DNS' = $vm2_dns
'New List IP' = $vm2_ip
}
}
} # End of NEW
if (-not $found){
$arr += [PSCustomObject]@{
Sno = $i
Status = " No match"
'Old List DNS' = $vm1_dns
'Old List IP' = $vm1_ip
Empty = ''
'New List DNS' = ''
'New List IP' = ''
}
}
}
$arr | Out-GridView
I think I would have used hashes. One set of hashes for IP/DNS, and one set for IP, for both old and new data sets (four hashes in all). Then just iterate over the keys in NEW and see if the key is in OLD. You can reverse the comparisons and use OLD to see if the key is in NEW if you need to. It's just set theory!
The "break" in your code was what was mostly causing you problems. You have multiple matches in NEW but each time you hit a match in OLD you jumped to the next OLD row, ignoring the other potential matches.