如何使用powershell脚本保持2个文件夹同步

时间:2014-09-16 13:15:00

标签: powershell

我们有两个文件夹:

  • FolderA:D:\ Powershell \ Original
  • FolderB:D:\ Powershell \ copy

现在,我想让FolderAFolderB保持同步(即当用户更改/添加/删除FolderA中的文件/目录时,FolderB中应该发生相同的更改1}})。

我试过了:

$Date = Get-Date 
$Date2Str = $Date.ToString("yyyMMdd") 
$Files = gci "D:\Powershell\Original" 
ForEach ($File in $Files){
        $FileDate = $File.LastWriteTime
        $CTDate2Str = $FileDate.ToString("yyyyMMdd")
        if ($CTDate2Str -eq $Date2Str) { 
           copy-item "D:\Powershell\Original" "D:\Powershell\copy" -recurse    
           -ErrorVariable capturedErrors -ErrorAction SilentlyContinue; 
        } 
}

但这需要类似的PowerShell脚本来删除FolderA中的文件和FolderB中的更改。

3 个答案:

答案 0 :(得分:31)

您是否看过Robocopy(强力文件复制)?它可以与PS一起使用并提供您所寻找的内容,即它专为可靠的复制或镜像文件夹(更改/添加/删除)而设计,只需根据需要选择选项即可。

Robocopy sourceFolder destinationFolder /MIR /FFT /Z /XA:H /W:5

/MIR选项镜像源目录和目标目录。如果在源处删除了文件,它将删除目的地的文件。

Robocopy

答案 1 :(得分:0)

我认为您应该尝试以下方法,它对我有用 根据您的要求更改syncMode。 1是用于目标的单向同步源,2是用于双向同步

    $source="The source folder" 
    $target="The target folder" 

    $sourceFiles=Get-ChildItem -Path $source -Recurse
    $targetFiles=Get-ChildItem -Path $target -Recurse

    $syncMode=2 

try{
$diff=Compare-Object -ReferenceObject $sourceFiles -DifferenceObject $targetFiles

foreach($f in $diff) {
    if($f.SideIndicator -eq "<=") {
        $fullSourceObject=$f.InputObject.FullName
        $fullTargetObject=$f.InputObject.FullName.Replace($source, $target)

        Write-Host "Attemp to copy the following: " $fullSourceObject
        Copy-Item -Path $fullSourceObject -Destination $fullTargetObject
    }


    if($f.SideIndicator -eq "=>" -and $syncMode -eq 2) {
        $fullSourceObject=$f.InputObject.FullName
        $fullTargetObject=$f.InputObject.FullName.Replace($target,$source)

        Write-Host "Attemp to copy the following: " $fullSourceObject
        Copy-Item -Path $fullSourceObject -Destination $fullTargetObject
    }

}
}      
  catch {
  Write-Error -Message "something bad happened!" -ErrorAction Stop
 }

答案 2 :(得分:0)

除了以前的答案以外,本文中有关您比较文件的方式也可能有所帮助。实际按内容比较文件需要额外的步骤。 (如哈希)。此方法的详细说明在此处编写: https://mcpmag.com/articles/2016/04/14/contents-of-two-folders-with-powershell.aspx

相关问题