How to Compare Two Files in PowerShell (With Example)


You can use the following basic syntax to compare two files in PowerShell:

$file1 = "c:\users\bobbi\teams1.txt"
$file2 = "c:\users\bobbi\teams2.txt"

diff (cat $file1) (cat $file2)

This particular example compares the differences between each of the rows in the text files named teams1.txt and teams2.txt.

The following example shows how to use this syntax in practice.

Example: How to Compare Two Files in PowerShell

Suppose we have the following file named teams1.txt that contains the names of various basketball teams:

And suppose we have another file named teams2.txt that contains the names of some more basketball teams:

Suppose that we would like to compare these two text files to identify the similarities and differences between them.

We can use the following syntax to do so:

$file1 = "c:\users\bobbi\teams1.txt"
$file2 = "c:\users\bobbi\teams2.txt"

diff (cat $file1) (cat $file2)

The following screenshot shows how to use this syntax in practice:

PowerShell compare two files

The output displays which values exist in only one of the text files.

The symbol => indicates that a particular value only exists in the second file.

From the output we can see that the following team names only exist in teams2.txt:

  • Jazz
  • Nets
  • Kings

Conversely, the symbol <= indicates that a particular value only exists in the first file.

From the output we can see that the following team names only exist in teams1.txt:

  • Spurs
  • Rockets
  • Knicks

If you only want to know the number of values that are different between the two files then you can use the following syntax:

$file1 = "c:\users\bobbi\teams1.txt"
$file2 = "c:\users\bobbi\teams2.txt"

(diff (cat $file1) (cat $file2)).count

The following screenshot shows how to use this syntax in practice:

We can see that there are 6 total values that are different between the two files.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Compare Two Arrays
PowerShell: How to Compare Dates
PowerShell: How to List Files in Directory by Date

Leave a Reply