Comparing two files using powershell


Hola todos,...

as it said in the heading, this is about comparing two files using powershell, I will get down to business and explain few things :

- normally two compare two files with powershell, there are two ways (which I know..) that we can use to do this, we can normally use the "Compare-object" CMDLET which was introduced by microsoft, this one can read the contents of both files and show you the difference in case there are some differences. if there are no differences it will show you nothing as a result (No prompts, messages or whatever..).

- The other way which i used to do before i knew the "Compare-object" CMDLET is to get the "length" property of each file and just make a condition saying of both lengths are equal, show some message, else show another message.

I will introduce both ways here :

#The code start here
# first code, using compare-object :

$source = "D:\we\f1.f"
$dest = "D:\f2.f"

Compare-Object -ReferenceObject (Get-Content $source) -DifferenceObject (get-content $dest) | fl

#The code ends here

- you can see that i am using the CMDLET, reading each content of both files using "Get-content" CMDLET and it will start comparing. At the end i am using "fl" which is the alias of "Format-list" CMDLET to show the differences in case there are any. if there are no differences it will simply show you nothing.

- the other way is to use the "Get-childItem" CMDLET, one of its properties is "length" property, we simply compare the "length" of each and every file and compare the lengths, if both are equal it means that files are similar,Example :

#Code start here
#The second code, using length:

$source = "D:\we\f1.f"
$dest = "D:\f2.f" 

$f1 = (Get-ChildItem -Path $source).length
$f2 = (Get-ChildItem -Path $dest).Length

if($f1 -eq $f2) {Write-Host "hell yeah!!"}else {Write-Host "hell no!!"}
#Code ends here

- the length property represents the size of the file in bytes, which means that any small change in the file such as removing a letter or a white space will actually change the "length" value.

- I guess I am done here, I am going to listen to some psychedelic rock, see ya all somewhere in time, Hasta luego..


Comments

Popular posts from this blog

IP Calculator in PowerShell...with IP exclusion