使用PowerShell比较子文件夹和复制文件

时间:2011-07-01 05:38:49

标签: powershell compare subdirectory

继续我之前的帖子: Comparing folders and content with PowerShell

...我正在尝试比较包含子文件夹的两个目录(至少4个级别)。第二个文件夹(folder2)包含我要复制到第三个文件夹(folder3)的新文件和更新文件。到目前为止,我的脚本没有按预期工作。第一个问题,需要在folder3中创建folder2中的子文件夹。做这个的最好方式是什么?此外,并非所有文件(新的或更新的)都从folder2复制到folder3。

无论如何,这是我的剧本:

$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}

1 个答案:

答案 0 :(得分:0)

我在下面做了一些改动似乎解决了我的问题。

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
    }