2

PowerShell Compare-Object SideIndicator

I have this code, which its output is not as intended

Compare-Object $(Get-Content c:\Folder\List1.txt) $(Get-Content 
c:\Folder\List2.txt) | 

Out-File C:\Folder\filename.txt 

I only want to get the " => SideIndicator " Values only not both . I.e what is different in list2

NGAHU MWANGI
  • 33
  • 1
  • 5

1 Answers1

3

Use the Where-Object cmdlet to filter by the SideIndicator property (PSv3+ syntax):

Compare-Object (Get-Content c:\Folder\List1.txt) (Get-Content c:\Folder\List2.txt) | 
  Where-Object SideIndicator -eq '=>' | 
    Out-File C:\Folder\filename.txt 

Also note how just (...) is sufficient to provide a single command or expression as an argument - no need for $(...).

Note:

  • Filtering by => outputs only those lines that are unique to the RHS (-DifferenceObject) collection; the SideIndicator property value (which is a string) points in the direction of the collection that a given object is unique to (assuming positional argument passing):

    • <= ... unique to the LHS (implied -ReferenceObject parameter)
    • => ... unique to the RHS (implied -DifferenceObject parameter)
    • == ... present in both collections (only with -IncludeEqual)
  • However, on output Compare-Object wraps the original objects by default, namely in a custom object that has a .SideIndicator property and an .InputObject property, the latter containing the original input object, which results in output such as:

    InputObject                   SideIndicator
    -----------                   -------------
    unique line 1 from List2.txt  =>
    unique line 2 from List2.txt  =>
    
  • To save just the lines in the output file, add the -PassThru switch to the Compare-Object call.

    • Note: The reason that filtering by the .SideIndicator property still works in this case is that with -PassThru the original objects are decorated with this property, using PowerShell's ETS (Extended Type System).

    • For strings, this extra property is ignored when they're saved to a file, such as with Out-File; however, in other scenarios it may surface; to prevent this:

      • Do not use -PassThru
      • Add an additional pipeline segment that pipes the Where-Object output to
        ForEach-Object InputObject, which outputs the undecorated original objects.
mklement0
  • 382,024
  • 64
  • 607
  • 775