Compare objects using PowerShell

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:\Temp\bulb.gif'
$sourceFile = 'D:\Temp\bulb2.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:\Temp\bulb.gif'
$targetFile = 'D:\Temp\bulb2.gif'

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

Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish