Reputation: 11
I have two folders
Both folder contain *.txt files with different numbered files names (eg. 01.txt, 02.txt...10.txt)
The script compares files present in both folders. Then only copies files from "Folder1" which aren't present in the "Folder2" or viceversa to C:\TestFolder.
For example if:
Then 02.txt would be the only file that is copied to C:\Testfolder.
I would to modify below script to add the following functionality:
Basically I need to check if the file present in Folder1 already exists in Folder2. Also verify if this file is the same, or if a newer version of a file/files are present in 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"
}
Upvotes: 0
Views: 1256
Reputation: 676
$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"
}
}
}
Upvotes: 0