希望经过一番尝试后可能会出现这样的结果?
$fileA = (Get-Content C:\temp\FileA.txt).Trim()
$fileB = (Get-Content C:\temp\FileB.txt).Trim()
Compare-Object $fileA $fileB -ExcludeDifferent -IncludeEqual | Tee-Object -Variable compareObject
$compareObject | ForEach-Object -Begin { "`n" } -Process { "Found $($_.InputObject) in both files!" }
输出
InputObject SideIndicator
----------- -------------
Big Cat ==
Monkey ==
Found Big Cat in both files!
Found Monkey in both files!
说明
假设管道实际上不是文件的一部分并且它们分开到自己的行中
$fileA = @"
Dog
Big Cat
Fish
Monkey
"@
$fileB = @"
Big Cat
Squirrel
Monkey
"@
以下几行获取每个文件的内容并将它们放入字符串数组中。然后.Trim() 方法从数组中每个项目的开头和结尾删除任何空格
$fileA = (Get-Content C:\temp\FileA.txt).Trim()
$fileB = (Get-Content C:\temp\FileB.txt).Trim()
接下来Compare-Object 将比较两个数组$fileA 和$fileB。通常Compare-Object 将只返回不同的对象并指出它们是在哪一侧找到的
InputObject SideIndicator
----------- -------------
Squirrel => # found only in $fileB
Dog <= # found only in $fileA
Fish <= # found only in $fileA
通过添加-ExcludeDifferent 和-IncludeEqual 标签,我们强制Compare-Object 只返回使用它在$fileA 和$fileB 中找到的值
InputObject SideIndicator
----------- -------------
Big Cat ==
Monkey ==
然后我们使用我们喜欢的任何输出。我想显示Compare-Object 的输出并用它做一些额外的任务,所以我将输出对象通过管道传送到Tee-Object -Variable somevariable。这会将输出发送到变量并沿着管道向下发送,在这种情况下,它只是输出到主机/屏幕
Compare-Object $fileA $fileB -ExcludeDifferent -IncludeEqual |
Tee-Object -Variable compareObject # set the $compareObject variable with results of Compare-Object
# and send down the pipe to host/screen
最后,我们循环遍历 Compare-Object 提供给我们的 2 个对象,它们在两个数组中都相等,并使用 InputObject 属性(如您在上面看到的包含我们正在寻找的值)制定我们的消息字符串
$compareObject | ForEach-Object -Begin { "`n" } -Process { "Found $($_.InputObject) in both files!" }
奖金
作为奖励,我最初认为 OP 想要比较包括管道在内的行中的项目,所以我写了这个。唯一的区别是我使用正则表达式在所有空格和管道中查找术语,包括来自Compare-Object 的所有比较,并且不要在末尾输出额外的字符串
$file1 = "| Dog | | Big Cat | | Fish | | Monkey | "
$file2 = "| Monkey | | Big Cat | | Squirrel |"
$matches1 = $file1 | Select-String -AllMatches '\|\s?(\w*\s?\w*)\s?\|\s?'
$file1Terms = foreach ($match in ($matches1.Matches)){ $match.Groups[1].Value.Trim() }
$matches2 = $file2 | Select-String -AllMatches '\|\s?(\w*\s?\w*)\s?\|\s?'
$file2Terms = foreach ($match in ($matches2.Matches)){ $match.Groups[1].Value.Trim() }
Compare-Object $file1Terms $file2Terms -IncludeEqual
输出
InputObject SideIndicator
----------- -------------
Big Cat ==
Monkey ==
Squirrel =>
Dog <=
Fish <=