Powershell Compare-Objects返回错误的结果

时间:2015-09-11 15:32:00

标签: powershell

我正在尝试使用此命令比较2个文件夹的内容:

Compare-Object (Get-ChildItem C:\compare -recurse) (Get-ChildItem J:\compare -recurse) -Property FullName

这是我应该得到的结果:

FullName                       SideIndicator
--------                       -------------         
J:\compare\test1.txt           =>                     
C:\compare\install.msi         <=           
C:\compare\setup.exe           <=                    
C:\compare\subfolder\test3.txt <=     

这是我实际得到的(我已经注意到两个文件夹中存在对象的位置,应该从比较中排除):

FullName                       SideIndicator
--------                       -------------
J:\compare\subfolder           => (exists in both folders)          
J:\compare\doc1.pdf            => (exists in both folders)           
J:\compare\doc2.pdf            => (exists in both folders)           
J:\compare\test1.txt           =>           
J:\compare\subfolder\test2.txt => (exists in both folders)           
C:\compare\subfolder           <= (exists in both folders)           
C:\compare\doc1.pdf            <= (exists in both folders)           
C:\compare\doc2.pdf            <= (exists in both folders)           
C:\compare\install.msi         <=           
C:\compare\setup.exe           <=           
C:\compare\subfolder\test2.txt <= (exists in both folders)           
C:\compare\subfolder\test3.txt <=  

为什么Powershell会将两个文件夹中存在的对象标记为不存在于任一文件夹中?就好像我在比较对象中使用-IncludeEqual(我不是),而不是我得到的==侧指示符&lt; =和=&gt;代替。

1 个答案:

答案 0 :(得分:1)

您的比较应该是

Compare-Object `
  (Get-ChildItem C:\Compare -Recurse | Select-Object -ExpandProperty FullName | Split-Path -NoQualifier) `
  (Get-ChildItem J:\Compare -Recurse | Select-Object -ExpandProperty FullName | Split-Path -NoQualifier)

这是因为,正如@TessellatingHeckler所指出的那样,两个路径之间的驱动器号(限定符)总是不同的,并且您想要忽略该部分。