Comparing folders and content with PowerShell

后端 未结 6 1470
广开言路
广开言路 2020-12-02 17:43

I have two different folders with xml files. One folder (folder2) contains updated and new xml files compared to the other (folder1). I need to know which files in folder2 a

6条回答
  •  时光说笑
    2020-12-02 18:05

    Further to @JNK's answer, you might want to ensure that you are always working with files rather than the less-intuitive output from Compare-Object. You just need to use the -PassThru switch...

    $Folder1 = Get-ChildItem "C:\Folder1"
    $Folder2 = Get-ChildItem "C:\Folder2"
    $Folder2 = "C:\Folder3\"
    
    # Get all differences, i.e. from both "sides"
    $AllDiffs = Compare-Object $Folder1 $Folder2 -Property Name,Length -PassThru
    
    # Filter for new/updated files from $Folder2
    $Changes = $AllDiffs | Where-Object {$_.Directory.Fullname -eq $Folder2}
    
    # Copy to $Folder3
    $Changes | Copy-Item -Destination $Folder3
    

    This at least means you don't have to worry about which way the SideIndicator arrow points!

    Also, bear in mind that you might want to compare on LastWriteTime as well.

    Sub-folders

    Looping through the sub-folders recursively is a little more complicated as you probably will need to strip off the respective root folder paths from the FullName field before comparing lists.

    You could do this by adding a new ScriptProperty to your Folder1 and Folder2 lists:

    $Folder1 | Add-Member -MemberType ScriptProperty -Name "RelativePath" `
      -Value {$this.FullName -replace [Regex]::Escape("C:\Folder1"),""}
    
    $Folder2 | Add-Member -MemberType ScriptProperty -Name "RelativePath" `
      -Value {$this.FullName -replace [Regex]::Escape("C:\Folder2"),""}
    

    You should then be able to use RelativePath as a property when comparing the two objects and also use that to join on to "C:\Folder3" when copying to keep the folder structure in place.

提交回复
热议问题