Powershell comparison of text file

309 views Asked by At

I'm just wondering if it's possible to compare two text file and check if there's a difference between them? What I mean is like this,

For example I have text1.txt :

123
456
789
000

and I have text2.txt :

123,test,input,bake
789,input,cake,bun

Expected output :

456 does not exist in text2.txt
000 does not exist in test2.txt

I'm new to this language (Powershell) I just have this code that getting the content of two text file and I don't know how to compare it.

$file1 = "C:\test\folder\test1.txt";
$file2 = "C:\test\folder\test2.txt";

$getfile1 = Get-Content $file1
$getfile2 = Get-Content $file2
1

There are 1 answers

3
dugas On BEST ANSWER

Something to get you started:

# $file1 will be an array with each element containing the line contents
$file1 = get-content .\text1.txt

# $file2 will be an array with each element containing the line contents just like $file1
$file2 = get-content .\text2.txt

# This splits each line of $file2 on the comma and grabs the first element and assigns it to the $file2FirstPart array.
$file2FirstPart = $file2 | ForEach-Object { $_.Split(',')[0] }

# This uses the Compare-Object cmdlet to compare the arrays.
$comparision = Compare-Object -ReferenceObject $file1 -DifferenceObject $file2FirstPart -Passthru

# This just displays the string you wanted to display for the comparison results
$comparison | ForEach-Object { "$($_) does not exist in text file 2" }

Good luck learning powershell!