How to Compare Two Folders in PowerShell (With Example)


You can use the following syntax in PowerShell to compare the contents of two folders:

$folder1 = Get-childitem "c:\users\bobbi\data1"
$folder2 = Get-childitem "c:\users\bobbi\data2"

Compare-Object $folder1 $folder2 -Property Name, Length  |
Where-Object {$_.SideIndicator -eq "<="} |
ForEach-Object {
    Copy-Item "c:\users\bobbi\data1\$($_.name)" -Destination "c:\users\bobbi\data3" -Force
}

Suppose that the folder named data1 contains the same files as data2, but some of the files in data1 have been updated with new data.

This particular syntax will find all of the files in data1 that are different than data2 and output them to a new folder named data3.

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

Example: How to Compare Two Folders in PowerShell

Suppose we have the following two folders named data1 and data2 in PowerShell:

We can see that the two folders have the same files but the length of some of the files is different between the two folders because data1 contains new data for some of the files.

Suppose that we would like to identify each of the files with new data in the folder named data1 and then automatically copy each of these files to a new folder named data3.

We can use the following syntax to do so:

$folder1 = Get-childitem "c:\users\bobbi\data1"
$folder2 = Get-childitem "c:\users\bobbi\data2"

Compare-Object $folder1 $folder2 -Property Name, Length  |
Where-Object {$_.SideIndicator -eq "<="} |
ForEach-Object {
    Copy-Item "c:\users\bobbi\data1\$($_.name)" -Destination "c:\users\bobbi\data3" -Force
}

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

PowerShell compare contents of two folders

Notice that we copied all updated files to the folder named data3 in the following location:

  • c:\users\bobbi\data3

When we run dir “c:\users\bobbi\data3” we are able to see the contents of this folder:

  • player_info.txt
  • task_info.txt

These two text files represent the two files that contained new data in the folder named data1 compared to data2.

Related Tutorials

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

PowerShell: How to List Files in Directory by Date
PowerShell: How to Get Most Recently Modified File in Directory
PowerShell: How to List All Files in Directory to Text File
PowerShell: How to Delete All Files with Specific Extension

Leave a Reply