Compare objects using PowerShell

Use PowerShell to compare objects.

John Savill

March 31, 2015

1 Min Read
Compare objects using PowerShell

Q. I want to compare objects using PowerShell, what are my options?

A. The Compare-Object cmdlet can be used to compare objects, for example:

$sourceFile = 'D:Tempbulb.gif'
$sourceFile = 'D:Tempbulb2.gif'

$sourceContent = Get-Content $sourceFile
$targetContent = Get-Content $targetFile

If ((Compare-Object –referenceobject $sourceContent –differenceobject $targetContent) –ne $null) {
    Write-Output "The files are different"
}

Another option is to check if hash values of files are different. For example:

$sourceFile = 'D:Tempbulb.gif'
$targetFile = 'D:Tempbulb2.gif'

if ((get-filehash $sourceFile).hash -ne (get-filehash $targetFile).hash) {
    Write-Output "The files are different"
}

About the Author

Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like