Home > Software design >  Copy recent/new files based on timestamp via PowerShell
Copy recent/new files based on timestamp via PowerShell

Time:12-03

Can you guys help me how can I compare the files in "Folder A" and "Folder B" via PowerShell and if the files are not present in "Folder B" based on the content of "Folder A", it will copy these missing files to "Folder C"? This is what I tried using the code from this link Powershell: Move files to folder based on Date Created but it doesn't have the comparison and it will copy all the files from "Folder A" to "Folder C". Thank you in advance.:

Get-ChildItem C:\Users\TestUser\Desktop\TEST\Folder A\*.xlsx -Recurse | foreach { 
$x = $_.LastWriteTime.ToShortDateString()
$new_folder_name = Get-Date $x -Format yyyy.MM.dd
$des_path = "C:\Users\TestUser\Desktop\TEST\Folder C\"

if (test-path $des_path){ 
    copy-item $_.fullname $des_path 
    } else {
    new-item -ItemType directory -Path $des_path
    copy-item $_.fullname $des_path 
    }
}

CodePudding user response:

Your question title and real question is not same, assuming that you only want to copy the missing files to third folder, here is the script below:

#Folder Path
$folderA = "C:\temp\folderA" 
$folderB = "C:\temp\folderB" 
$destination = "C:\temp\folderC\"

#Getting File names only from source and folder to be compared
$sourceFolder = Get-childItem -path $folderA | Select-Object -ExpandProperty Name
$foldertobeCompared = Get-childItem -path $folderB | Select-Object -ExpandProperty Name

# comparing files and copying to third folder
foreach ($file in $sourceFolder) {
    if ($foldertobeCompared -contains $file) {
    Write-Host "$($file) exists in folderB"
   } else {
   Copy-Item -Path "$folderA\$file" -Destination $destination
   Write-Host "$($file) copied in folderC" 
   }

}
  • Related