PowerShell Compare-Object
Compare-Object in PowerShell
The Compare-Object cmdlet in PowerShell is used to compare two sets of objects and find the differences between them. This can be particularly useful for comparing files, strings, or arrays to determine how they differ. Here’s an explanation and a few examples demonstrating how Compare-Object works.
WinRM Access Check using Compare-Object
# Get list of enabled computers from Active Directory
$ComputerList= Get-Adcomputer -filter * | ?{$_.Enabled -eq $True} | Select -ExpandProperty Name
# Command to Check for Systems online that respond to WinRM
$ComputersConnected=Invoke-Command -ComputerName $ComputerList -ScriptBlock {$Env:COMPUTERNAME}
# Compare full list to see if any did not respond
$Tested=Compare-Object -ReferenceObject $ComputerList -DifferenceObject $ComputersConnected -IncludeEqual
# Filter to get systems that were accessible
$TestPassConn=$Tested | ?{$_.SideIndicator -eq "=="} | Select -ExpandProperty InputObject
# Filter to get systems that are NOT accessible
$TestFailConn=$Tested | ?{$_.SideIndicator -eq "<="} | Select -ExpandProperty InputObject
# Results Out to screen and file
Write-Host '--Failed--'
$TestFailConn | Tee-Object C:\temp\TestFailedWInRM.txt
# Results Out to screen and file
Write-Host '--Passed--'
$TestPassConn | Tee-Object C:\temp\TestPassWinRM.txt