我有两个文件夹
两个文件夹都包含具有不同编号文件名的* .txt文件(例如,01.txt,02.txt ... 10.txt)
该脚本会比较两个文件夹中的文件。然后只复制“Folder1”中不存在于“Folder2”中的文件或反之为C:\ TestFolder。
例如:if:
然后02.txt将是唯一复制到C:\ Testfolder的文件。
我想在下面的脚本中修改以添加以下功能:
基本上我需要检查Folder1中存在的文件是否已存在于Folder2中。同时验证此文件是否相同,或者Folder2中是否存在较新版本的文件/文件。
Compare-Object $Folder1 $Folder2 -Property Name, Length , LastWriteTime | Where-Object {$_.SideIndicator -eq "<="} | ForEach-Object {
Copy-Item "C:\Source\$($_.name)" -Destination "C:\TestFolder" -Force -recurse -include "*.txt"
}
答案 0 :(得分:0)
$folder1="c:\folder1"
$folder2="c:\folder2"
$dest="c:\testfolder"
$folder1Files=dir $folder1
$folder2Files=dir $folder2
$newestFileFolder2=$folder2Files | sort LastWriteTime | select -expand LastWriteTime -Last 1
$equalFiles=diff $folder1Files $folder2Files -Property Name,Length -ExcludeDifferent -IncludeEqual -PassThru | select Name,LastWriteTime,FullName
foreach ($file in $equalFiles){
#If the file present in Folder1 is newer then "all" the files in Folder2: do nothing
if ($file.LastWriteTime -lt $newestFileFolder2){
#If the file in the Folder1 is newer then "some" of the file on the Folder2: copy the newer files to Folder3.
if ((dir "$folder2\$($file.Name)").LastWriteTime -gt $file.LastWriteTime){
copy "$folder2\$($file.Name)" $dest -Force -recurse -include "*.txt"
}
else{
copy "$($file.FullName)" $dest -Force -recurse -include "*.txt"
}
}
}