问题描述
在这里,我试图比较2个文件夹,然后递归地将差异复制到第三个文件夹中。
下面是我的代码,我能够完成大部分工作,但无法像在Folder1中那样将文件复制到精确的文件夹结构中。该脚本实际上将文件直接复制到folder3上,而没有任何文件夹。这只是从不同的文件夹中单独复制文件,然后将其放入文件夹3。任何帮助将不胜感激。
$Folder1path = "M:\Technical\foldercompare\folder1"
$Folder2path = "M:\Technical\foldercompare\folder2"
$Folder3path = "M:\Technical\foldercompare\folder3"
$Folder1 = Get-childitem -path $Folder1path -Recurse
$Folder2 = Get-childitem -path $Folder2path -Recurse
Compare-Object -ReferenceObject $folder1 -DifferenceObject $Folder2
Compare-Object $Folder1 $Folder2 -Property Name,Length |
Where-Object {$_.SideIndicator -eq "<="} |
ForEach-Object {
Copy-Item "$Folder1path\$($_.name)" -Destination "$Folder3path" -Force -Recurse
}
解决方法
下面的脚本代表了您执行任务的一种方式(假设您的3个目录共享一个公共的父目录)。顺便说一句,您最初的尝试未能处理$null
或$Folder1Path
为空时发生的$Folder2Path
。
# Files in 1 but not in 2 should wind up in 3 with the same dir structure as occurs in 1
param(
$Folder1path = "$PSScriptRoot\folder1",$Folder2path = "$PSScriptRoot\folder2",$Folder3path = "$PSScriptRoot\folder3"
)
$ErrorActionPreference = "Stop";
Set-StrictMode -Version 'Latest'
Get-ChildItem -Path $Folder1Path -Recurse | Where-Object {
[string] $toDiff = $_.FullName.Replace($Folder1path,$Folder2path)
# Determine what's in 2,but not 1
[bool] $isDiff = (Test-Path -Path $toDiff) -eq $false
if ($isDiff) {
# Create destination path that contains folder structure
$dest = $_.FullName.Replace($Folder1path,$Folder3path)
Copy-Item -Path $_.FullName -Destination $dest -Verbose -Force
}
}