简体   繁体   中英

Comparing Sub-Folders and Copying Files with PowerShell

In continuation from my previous post here: Comparing folders and content with PowerShell

...I'm attempting to compare two directories that contain sub-folders (at least 4 levels deep). The second folder (folder2) contains new and updated files that I want to copy to a third folder (folder3). So far my script isn't quite working as expected. First problem, the sub-folders in folder2 need to be created in folder3. What is the best way to do this? Also, not all files (new or updated) are getting copied to folder3 from folder2.

Anyway, here is my script:

$Folder1 = "D:\folder1" 
$Folder2 = "D:\folder2"
$Folder3 = "D:\folder3"

function Get-Directories ($path)
{
    $PathLength = $path.length
    gci $path -rec | % {
        Add-Member -InputObject $_ -MemberType NoteProperty -Name RelativePath -Value $_.FullName.substring($PathLength+1)
        $_
    }
}

Compare-Object (Get-Directories $Folder1) (Get-Directories $Folder2) -prop RelativePath, Name, Length |
Sort RelativePath, Name, Length -desc | % {
if ($file -ne $_.RelativePath)
{ $_ }
$file = $_.RelativePath
} | Where-Object {$_.SideIndicator -eq "=>"} | ForEach-Object {Copy-Item ("$Folder2\" + $file) -Destination ("$Folder3\" + $file) -Force}

I made some changes below which seems to solve my problem.

function Get-Directories ($path)
{
    $PathLength = $path.length
    Get-ChildItem $path -Recurse | % {
        Add-Member -InputObject $_ -MemberType NoteProperty -Name RelativePath -Value $_.FullName.substring($PathLength+1)
        $_
    }
}

Compare-Object (Get-Directories $Folder1) (Get-Directories $Folder2) -Property RelativePath, Name, Length |
Sort RelativePath, Name, Length -desc | % {
    if ($file -ne $_.RelativePath) { $_ } } | 
    Where-Object {$_.SideIndicator -eq "=>"} | 
    ForEach-Object {
        $file = $_.RelativePath
        Echo F | xcopy "$Folder2\$file" "$Folder3\$file" /S
    }

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