I was hoping someone would be able to help with the problem that I encountered in comparing arrays.
Here is some background. I have a powershell script that generates a list of domain controllers, checks to see if they are online, and then writes data to a csv file. It works great.
I want to run this week and send a warning if any domain controllers are added or removed.
I have another script that imports the previously generated CSV into an array, then I create a new list of domain controllers and send this list to a new array. I am trying to compare these two using compare-object and export a new CSV with a list of differences.
However, I test this by manually modifying the old CSV, and I find that no matter which domain controller I remove from the previous list or where I add a new one, it always reports that this change is the last domain controller in 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 checked this by deleting "dc3.testcompany.com", "online" and running the script again, he knows that the list has changed, but he reports that the new entry is "dc4.testcompany.com", "online" and not "dc3.testcompany.com", "online".
Similarly, if I change 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"
he will report that the one that is different from the new list is "dc4.testcompany.com", "online", and not the one I added in the middle.
I have to do something wrong with my comparison. Here is the important 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 " xxxx@xxxxxxxx.com " –To " xxxx@xxxxxxxx.com " –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!
Thanks! John