Home ยป Compare Two Files in PowerShell

Compare Two Files in PowerShell

In PowerShell, you can compare two text files content using the Compare-Object cmdlet.

The Compare-Object cmdlet with the DifferenceObject parameter, you can compare two files.

In the following script, the Get-Content cmdlet read the content of file and stores them in $file1Content and $file2Content variables.

The Compare-Object cmdlet uses the -ReferenceObject and -DifferenceObject to compare the content of two files and output the differences in $differences variable.

If-Else statement used to check if there are differences in text files and print the differences if any difference found in the file else prints “Files ae equal“.

$file1Content = Get-Content -Path "C:\temp\file1.txt"
$file2Content = Get-Content -Path "C:\temp\file2.txt"

$differences = Compare-Object -ReferenceObject $file1Content -DifferenceObject $file2Content

if ($differences) {
    Write-Host "Files are not equal"
    $differences | ForEach-Object {
        if ($_.SideIndicator -eq "<=") {
            Write-Host "Line '$($_.InputObject)' is missing in the second file."
        } else {
            Write-Host "Line '$($_.InputObject)' is missing in the first file."
        }
    }
} else {
    Write-Host "Files are equal"
}

Result:

Files are equal

Conclusion

I hope the above article on how to use Compare-Object cmdlet to compare the content of two files in PowerShell is helpful to you.

You can find more topics about Active Directory tools and PowerShell basics on the ActiveDirectoryTools home page.