Note:
This answer does not address what the OP was ultimately looking for.
Instead, it shows how to add a column to Compare-Object
's output that shows for each difference object (line) the full path of the file that the line is exclusive too. Perhaps it is useful to some future readers.
You can take advantage of the fact that Get-Content
decorates its output lines with a .PSPath
property (among others) that contains the source file's full path:
Compare-Object (Get-Content D:\Folder1\file1.js) (Get-Content D:\Folder2\file1.js) |
Select-Object InputObject,
SideIndicator,
@{ n = 'Path'; e = { $_.InputObject.PSPath } }
Note the use of a calculated property to add a Path
property to the output objects.
Select-Object
creates new objects with the specified properties.
An alternative - for display only, if you additionally need to preserve the original output objects with, say, Compare-Object ... -OutVariable results
- is to use Format-Table
.
If, for any block of difference lines from the same file, you only want to print the path for the first line in the block, more work is needed, using an aux. variable in the caller's scope:
$prevPath = ''
Compare-Object (Get-Content D:\Folder1\file1.js) (Get-Content D:\Folder2\file1.js) |
Select-Object InputObject,
SideIndicator,
@{
Name = 'Path'
Expression = {
if ($_.InputObject.PSPath -ne $prevPath) {
(([ref] $prevPath).Value = $_.InputObject.PSPath)
}
}
}
Note:
The Expression
script block runs in a child scope of the caller, so directly assigning to $prevPath
would create a local variable that goes out of scope after every script block invocation.
- Assigning to
([ref] $prevPath).Value
instead is a convenient, albeit somewhat obscure way to refer to the $prevPath
in the parent scope, i.e. the caller's.
It is the equivalent of using the more verbose (Get-Variable -Scope 1 prevPath).Value
Enclosing the assignment in (...)
passes the assigned value through, i.e. also outputs the value.
Note: Use of Format-Table
would be preferable in this case, given that the output modification is only for display purposes.
However, up to at least PowerShell 7.3.4 a long-standing bug prevents that - see GitHub issue #19509