2020 | Scott W. Head  |  Sr. Systems Admin | Certified Microsoft Windows Server Administrator

PowerShell Compare-Object

Compare-Object can be used to find the difference in lists / arrays and displays what items are not in the $MyLocalServices list. So it would show all services that are not running. This is a simple display of comparing data which is needed to be completed from time to time so this Compare-Object is one of the most valuable Cmdlets I use.


#|||||||||||||||||||||||||||||||||||||||||||||||| Compare-Object to Find Differences ||||||||||||||||||||||||||||||||||||||||||||


$Exclusion_List=''
$FullList=''
#Build Arrays
$Exclusion_List=@()
$FullList=@()

$Exclusion_List+='2000','2010','2009','2020'
$FullList+='2000','2003','2008','2010','2016'

CLS

#Compare the two and display items from Exclusion list not found in the Full List
$Results_A=Compare-Object -ReferenceObject $FullList -DifferenceObject $Exclusion_List | ? {$_.SideIndicator -eq '=>'} | Select -ExpandProperty inputobject -ErrorAction Stop


#Compare the two and display items from Full list not found in the in the Exlsion List
$Results_B=Compare-Object -ReferenceObject $FullList -DifferenceObject $Exclusion_List | ? {$_.SideIndicator -eq '<='} | Select -ExpandProperty inputobject -ErrorAction Stop


#Compare the two and display items found in both lists
$Results_C=Compare-Object -ReferenceObject $FullList -DifferenceObject $Exclusion_List -IncludeEqual -ExcludeDifferent | Select -ExpandProperty inputobject -ErrorAction Stop


write-output '----------Exclusion list items not found in the Full List-------------'
$Results_A

write-output '----------Full list items not found in the in the Exclusion List------'
$Results_B

write-output '----------Items found in both lists ----------------------------------'
$Results_C


        #|||||||||||||||||||||||||||||||||||||||||||||  Compare-Object with ServerNames |||||||||||||||||||||||||||||||||||||||||||||||||||
        $Exclusion_List=@()
        $Exclusion_List='Server1','Server2','Server3'


        $System=Get-ADComputer -Properties * -SearchBase 'OU=MyOU,DC=MyDomain,DC=com' -Filter '*' |

        Where-Object {($_.OperatingSystem -Like 'Windows Server 2008*') -and ($_.Enabled -eq $True)} | Select -ExpandProperty Name


        #//////////// Compare the two sources and remove all items matched in the exclusion var \\\\\\\\\\\\\\\\\\\
        Compare-Object -ReferenceObject $Exclusion_List -DifferenceObject $System  | Select -ExpandProperty inputobject -ErrorAction Stop