简体   繁体   中英

Powershell Compare-Objects returns wrong results

I'm trying to compare the contents of 2 folders using this command:

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

This is the result that I should get:

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

This is what I actually get (I've noted where objects exist in both folders and should be excluded from the comparison):

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 <=  

Why is Powershell flagging objects that exist in both folders as not existing in either folder? It's as if I'm using -IncludeEqual with Compare-Object (which I'm not), but instead of the == side indicators I'm getting <= and => instead.

Your comparison should be

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)

This is because, as @TessellatingHeckler noted, the drive letters (qualifiers) are always different between the two paths, and you want to ignore that part.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM