Compare two text files with duplicates and write t

2019-09-01 03:16发布

问题:

I want to compare 2 text files and output the difference in another text file.

compare-object (get-content c:\temp\hostname_old.txt) (get-content c:\temp\hostname_new.txt) | Select-Object -ExpandProperty InputObject | Out-File $Location

hostname_old.txt

server02
server05
server04
server06
server01

hostname_new.txt (has duplicate names)

server04
server01
server02
server04
server02

Result:

server04
server02
server05
server06

Note how server04 and server02 are present in this list of differences, even though they're present in both input files.

This is what I want:

server05
server06

回答1:

Use Select-Object -Unique to eliminate the duplicates before comparing:

compare-object -PassThru `
  (get-content c:\temp\hostname_old.txt) `
  (get-content c:\temp\hostname_new.txt | Select-Object -Unique)

As in this answer to your previous question, -PassThru is used to pass out the differing lines directly, without the [pscustomobject] wrappers (that indicate the source set of the difference via their .SideIndicator property) that Compare-Object outputs by default.