How To: Compare two text files with PowerShell

Intro

This post shows the code to compare two text files and determine whether the content is identical or not, as well as listing a line by line comparison. This utility could be useful to verify some scenarios, such as migrations, upgrades.

Comparing two files with PowerShell

The script below takes two files stored in the Desktop, compares their content, and prints a message to determine whether they are identical or not.

$desktopFolder = [Environment]::GetFolderPath("Desktop")
$fileA = "$desktopFolder\FileA.txt"
$fileB = "$desktopFolder\FileB.txt"

If (Compare-Object -ReferenceObject $(Get-Content $fileA) -DifferenceObject $(Get-Content $fileB))
{
  Write-Host "Different" -foregroundcolor red
}
Else
{
  Write-Host "Identical" -foregroundcolor green
}

The second script compares two files and provides a line by line comparison.

$desktopFolder = [Environment]::GetFolderPath("Desktop")
$fileA = "$desktopFolder\FileA.txt"
$fileB = "$desktopFolder\FileB.txt"

Compare-Object $(Get-Content $fileA) $(Get-Content $fileB) -includeequal

Reference

Using the Compare-Object Cmdlet – TechNet

Advertisements

Author: Luis Carrazana

Skilled Senior Technology Consultant and Strategist, with a decade of experience advising and assisting customers from small and large companies, including Fortune 500. Luis is a Microsoft Certified Professional with extensive experience in .NET framework and SharePoint development.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s