I was hoping someone would be able to help with a problem I've been running into comparing arrays.
Here's some background. I have a powershell script that generates a list of domain controllers, checks to see if they are online and then writes the data to a csv file. This works fine.
I want to run this weekly and send an alert if any domain controllers are added or removed.
I have another script that imports the previously generated CSV to an array, then I generate a new list of domain controllers and send that list to a new array. I am attempting to compare the two using compare-object, and export a new CSV with a list of differences.
However, I'm testing this by manually modifying the old CSV, and I've found that no matter which domain controller I remove from the previous list or where I add a new one, it always reports that the change is the last domain controller on the list.
For example, here's what my CSV file looks like:
"DC_Name","Ping_Response"
"dc1.testcompany.com","online"
"dc2.testcompany.com","online"
"dc3.testcompany.com","online"
"dc4.testcompany.com","online"
If I test this by deleting "dc3.testcompany.com","online" and running the script again, it knows that the list has changed, but it reports that the new entry is "dc4.testcompany.com","online" and not "dc3.testcompany.com","online".
Similarly, if I modify my old csv to look like this:
"DC_Name","Ping_Response"
"dc1.testcompany.com","online"
"dc2.testcompany.com","online"
"dc5.testcompany.com","online"
"dc3.testcompany.com","online"
"dc4.testcompany.com","online"
it will report that the one that is different from the new list is "dc4.testcompany.com","online", not the one I've added in the middle.
I must be doing something wrong with my comparison. Here is relevant part of the script I'm using:
$newDCArray = @(Import-CSV DC_List.csv)
$oldDCArray = @(Import-CSV Last_DC_List.csv)
$diff = Compare-Object $oldDCArray $newDCArray
if($diff -eq $null)
{
Write-Host "No changes to DCs"
}
else
{
Write-Host "There have been changes to DCs"
$diff| Export-CSV DC_Change_List.csv -notypeinformation
Send-MailMessage –From "[email protected]" –To "[email protected]" –Subject "Alert - Domain Controllers Added or Removed" –Body "DC Report Attached" –SmtpServer "smtp.xxxxxxxxxxx.net" -Attachments "DC_Change_List.csv"
}
Please let me know if anyone has any ideas!
Thank you! John