问题
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
回答1:
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; theSideIndicatorproperty 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-ReferenceObjectparameter)=>... unique to the RHS (implied-DifferenceObjectparameter)==... 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
.SideIndicatorproperty and an.InputObjectproperty, 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
-PassThruswitch to the Compare-Object call.Note: The reason that filtering by the
.SideIndicatorproperty still works in this case is that with-PassThruthe 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-Objectoutput toForEach-Object InputObject, which outputs the undecorated original objects.
- Do not use
来源:https://stackoverflow.com/questions/53361968/powershell-compare-object-sideindicator