HS Banner
Back
Compare two text files

Author: Admin 03/26/2021
Language: PowerShell
Tags:


Description:

Compare two text files and display the differences.

Article:

param(
	[string]$file1,
	[string]$file2,
	[switch]$All,
	[switch]$h,
	[parameter( ValueFromRemainingArguments = $true )]
	[string]$invalidArgs
)
 
 
function Show-Help {
	param ( [string]$errormessage )
 
	if ( $errormessage -ne "" ) {
		Write-Host
		Write-Host "Error: " -ForegroundColor Red -NoNewline
		Write-Host $errormessage -ForegroundColor White
	}
 
	Write-Host
	Write-Host "TxtComp.ps1,  Version 1.01"
	Write-Host "Compare two text files and display the differences"
	Write-Host
	Write-Host "Usage:  " -NoNewline
	Write-Host "powershell ./TxtComp.ps1  file1  file2  [ -All ]" -ForegroundColor White
	Write-Host
	Write-Host "Where:  " -NoNewline
	Write-Host "file1 " -ForegroundColor White -NoNewline
	Write-Host "and " -NoNewline
	Write-Host "file2" -ForegroundColor White -NoNewline
	Write-Host "    are the files to be compared"
	Write-Host "        -All               " -ForegroundColor White -NoNewline
	Write-Host "displays " -NoNewline
	Write-Host "All " -ForegroundColor White -NoNewline
	Write-Host "lines, not just the differences"
	Write-Host
	Write-Host "Written by Rob van der Woude"
	Write-Host "http://www.robvanderwoude.com"
	Write-Host
 
	Exit 1
}
 
 
$file1 = "$file1".Trim( )
$file2 = "$file2".Trim( )
 
if ( $h -or ( $file1 -eq "" ) -or ( $file1 -eq "/?" ) -or ( $file1 -eq "--help" ) -or ( $file2 -eq "/?" ) -or ( $file2 -eq "--help" ) ) {
	Show-Help
}
 
if ( $file2 -eq "" ) {
	Show-Help "Please specify TWO files to compare"
}
 
if ( [string]$invalidArgs -ne "" ) {
	if ( ( $invalidArgs -eq "/?" ) -or ( $invalidArgs -eq "--help" ) ) {
		Show-Help
	} else {
		Show-Help "Invalid command line argument(s)"
	}
}
 
if ( $file1 -eq $file2 ) {
	Show-Help "Cannot compare a file to itself"
}
 
if ( -not ( Test-Path $file1 ) ) {
	Show-Help "File `"$file1`" not found"
}
 
if ( -not ( Test-Path $file2 ) ) {
	Show-Help "File `"$file2`" not found"
}
 
if ( ( $file1 -eq $file2 ) -or ( $file1 -eq "" ) -or ( $file2 -eq "" ) ) {
	Show-Help
}
 
Compare-Object $( Get-Content $file1 ) $( Get-Content $file2 ) -IncludeEqual:$All



Back
Comments
Add Comment
There are no comments yet.