我们有两个文件夹:
FolderA
:D:\ Powershell \ Original FolderB
:D:\ Powershell \ copy 现在,我想让FolderA
和FolderB
保持同步(即当用户更改/添加/删除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
中的更改。
答案 0 :(得分:31)
您是否看过Robocopy(强力文件复制)?它可以与PS一起使用并提供您所寻找的内容,即它专为可靠的复制或镜像文件夹(更改/添加/删除)而设计,只需根据需要选择选项即可。
Robocopy sourceFolder destinationFolder /MIR /FFT /Z /XA:H /W:5
/MIR
选项镜像源目录和目标目录。如果在源处删除了文件,它将删除目的地的文件。
答案 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