【问题标题】:Sync Folders With PowerShell使用 PowerShell 同步文件夹
【发布时间】:2017-10-11 08:47:30
【问题描述】:

我试试这个脚本来同步 2 个文件夹

$Folder1Path = 'C:\test1'
$Folder2Path = 'C:\test2'
$folder1Files = Get-ChildItem -Recurse -path $Folder1Path
$folder2Files = Get-ChildItem -Recurse -path $Folder2Path
$file_Diffs = Compare-Object -ReferenceObject $folder1Files -DifferenceObject $folder2Files
$file_Diffs | foreach {
$copyParams = @{'Path' = $_.InputObject.FullName}
if($_.SideIndicator -eq '<=' )
{$copyParams.Destination = $Folder2Path}
copy-Item @copyParams -force
}

但是当脚本在 test2 下复制文件时我遇到了一个问题,它不尊重正确的路径:

在文件夹 test1 我有: test1\test3\test4.txt 和 test1\test5.txt 在文件夹 test2 我有: test2\test5.txt

当我执行我的脚本时,我在文件夹 test2 中找到 测试2\测试5.txt 测试2\测试4.txt 测试2\测试3

【问题讨论】:

  • 你最好在这里使用 robocopy
  • 我如何使用 robocopy ??
  • 如果您希望 $folder2 成为 $folder1 的精确副本,请执行此操作robocopy.exe $folder1 $folder2 /MIR
  • 我尝试 robocopy 我的脚本是这样的: $Folder1Path = 'C:\test1' $Folder2Path = 'C:\test2' robocopy $Folder1Path $Folder2Path /COPYALL /B /SEC /MIR /R :0 /W:0 /NFL /NDL /NJH /NJS
  • 如何在 powershell 中定义 crone 以使其自动工作???

标签: powershell


【解决方案1】:

您将Copy-Item 的目标设置始终为'C:\test1'。这将忽略源文件的任何更深层次的文件夹结构。如果要保留源的文件夹结构,则需要相应地调整文件的 FullName 属性:

$Folder1Path = 'C:\test1'
$Folder2Path = 'C:\test2'
$folder1Files = Get-ChildItem -Recurse -path $Folder1Path
$folder2Files = Get-ChildItem -Recurse -path $Folder2Path
$file_Diffs = Compare-Object -ReferenceObject $folder1Files -DifferenceObject $folder2Files
$file_Diffs | 
  foreach {
     $copyParams = @{'Path' = $_.InputObject.FullName}
     if($_.SideIndicator -eq '<=' )
     { 
         $copyParams.Destination = $_.InputObject.FullName -replace [regex]::Escape($Folder1Path),$Folder2Path
     }
     copy-Item @copyParams -force
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-31
    • 2022-07-04
    • 1970-01-01
    • 2020-01-14
    • 2016-05-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多