Compare-Object and ignore white space

I’m trying to compare text files and all I care about is that the text within is the same, I don’t care about white space or case sensitivity. Is there a way to do this with Compare-Object? I’m not seeing that there is, but if there is a way, please let me know…


Try this
Compare-Object $(Get-Content c:\scripts\x.txt) $(Get-Content c:\scripts\y.txt)

It will give you input like this if there is any changes.

PS C:> Compare-Object $(Get-Content c:\x1.txt) $(Get-Content c:\y1.txt)

InputObject SideIndicator

abcd =>
abc <=

I tried this, I gives me all the white space differences…I’m trying to ignore white space

By default it’s not case sensitive, if you wanted it to be you could specify the -CaseSensitive parameter.

To ignore the whitespace, try using the trim() method.

Compare-Object -ReferenceObject (get-content c:\ref.txt) -DifferenceObject (Get-Content c:\diff.txt).trim() -IncludeEqual

Edit: I left the -IncludeEqual there just to prove my test files worked, you may want to remove it if you’re looking for differences.

  1. Get-Content creates a PSObject and basically creates each line as an individual object
  2. Compare-Object is going to compare each line of the object to see if it matches or one object contains a value the other does not with a side indicator

If you want to compare these individual items, I would remove anything required prior to using Compare-Object. Maybe something like this:

Get-Content Test.txt | foreach{ $_.Trim()

this worked for me:

Compare-Object -ReferenceObject ((get-content c:\ref.txt).trim()) -DifferenceObject ((Get-Content c:\diff.txt).trim())