Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell File Compare

Tags:

powershell

I am using a PowerShell script to move some files around on some servers. I want to test if a file I am going to move already exists in the destination. Not just a file with the same name.

I thought

Compare-Object $File1 $File2
Should do it but no matter what the files are it always returns that they are the same eg.

InputObject           SideIndicator                              
-----------           -------------                              
D:\1.gif               =>                                         
D:\1.wma               <=    

Is there some other way to test if two files are identical?

like image 574
zebidy Avatar asked Aug 16 '10 05:08

zebidy


People also ask

How do you compare two things in PowerShell?

To check to see if one object is equal to another object in PowerShell is done using the eq operator. The eq operator compares simple objects of many types such as strings, boolean values, integers and so on. When used, the eq operator will either return a boolean True or False value depending on the result.

Is there a diff command in PowerShell?

The DIFF binary is not available in PowerShell (although there is a DIFF alias). However there are two commands that are built into Windows and that have been available since the days of CMD. EXE. These two built in commands are FC.


3 Answers

(Get-FileHash $path1).Hash -eq (Get-FileHash $path2).Hash
like image 198
Diou KF Avatar answered Sep 20 '22 06:09

Diou KF


I guess it's going to depend on your definition of "The same"

Compare-Object (ls Source\Test.*) (ls Dest\Test.*) -Property Name, Length, LastWriteTime

That will compare the actual FILE objects by name, length, and modified date. Adding -IncludeEqual will result in also showing ones that are the same in both places.

If you want to only copy files from "Source" which aren't the same in the "Destination" just do this:

Compare-Object (ls $Source) (ls $Destination) -Property Name, Length, LastWriteTime -passthru | 
Where { $_.PSParentPath -eq (gi $Source).PSPath } |
Copy-Item $Destination

DO NOT start writing scripts that get-content (as suggested by others) to do a file comparison -- you'd be loading everything into memory...

DO consider using robocopy (even though it's command-line syntax is dated). =Þ

like image 36
Jaykul Avatar answered Sep 19 '22 06:09

Jaykul


You're just giving two strings to Compare-Object, you want the file contents:

Compare-Object (gc $File1) (gc $File2)

Also the output you're giving does not mean that the files are the same.

like image 25
Joey Avatar answered Sep 22 '22 06:09

Joey