Comparing two records and sending an email when there is a match

Hi,

I have two systems, from which I pull the list of servers in real time.
The result from the first system ($adservers) is:

Name ManagedBy


Server1 Dan@gmail.com
Server2 Rob@gmail.com
Server3
Server4 Tom@gmail.com

The result from the second system ($cmservers) is:

Name

Server2
Server3
Server4

Now I want to send an email to the owners of the servers that appear in both the first and second list and if the first list does not include the email of the server owner (Server3) then send me the email.

This is what I wrote, but I’m probably missing something:

foreach ($server in $cmservers)
{

   $Owner =  $adservers | where {$_.Name -eq $server.name}|  select -ExpandProperty ManagedBy
   if($Owner){
    Send-MailMessage -To "$($owner)" -Subject "$($Server.Name) is pending reboot!" -SmtpServer mail.mydomain.com -from it@mydomain.com
   }
   else{
   
     Send-MailMessage -To "it@mydomain.com" -Subject "$($Server.Name) :The manager is not defined!" -SmtpServer mail.mydomain.com -from it@mydomain.com
   
   }

}

Thanks

Why do you think that? Doesn’t it work as expected?

Anyway … may I suggest another approach?

$ServerList = 
Compare-Object -ReferenceObject $adservers -DifferenceObject $cmservers -Property Name -IncludeEqual -ExcludeDifferent

foreach ($Server in $ServerList) {
    $SendMailMessageProps = @{
        Subject    = "$($Server.Name) :The manager is not defined!"
        SmtpServer = 'mail.mydomain.com'
        from       = 'it@mydomain.com'
        To         = ''
    }
    if ($Server.Owner) {
        $SendMailMessageProps.To = $Server.Owner
    }
    Else {
        $SendMailMessageProps.To = 'it@mydomain.com'
    }
    Send-MailMessage @SendMailMessageProps
}

… untested. :wink:

1 Like