1

I found a code here (on this site) which allows copying of files changed in last 20 days. My issue is that I have a folder with many subfolders and some subfolders could be 8 or more levels deeps. I need to copy files changed to destination folder and maintain the folder structure. How could this be changed to allow recursively copy files and maintain same folder structure. Below is code:

$DestinationFolder = "c:\temp1\"
$EarliestModifiedTime = (Get-date).AddDays(-20)
$Files = Get-ChildItem "c:\temp\*.*" 
foreach ($File in $Files) {
    if ($File.LastWriteTime -gt $EarliestModifiedTime)
    {
        Copy-Item $File -Destination $DestinationFolder
        Write-Host "Copying $File"
    }
    else 
    {
        Write-Host "Not copying $File"
    }
}

2 Answers 2

2

I think this should work for your need. Utilizing Get-ChildItem -Recurse and keeping the folder structure with the $RelativePath:

$SourceFolder = "c:\temp\"
$DestinationFolder = "c:\temp1\"
$EarliestModifiedTime = (Get-Date).AddDays(-20)
$Files = Get-ChildItem $SourceFolder -Recurse -File

foreach ($File in $Files) {
    if ($File.LastWriteTime -gt $EarliestModifiedTime) {
        $RelativePath = $File.FullName.Substring($SourceFolder.Length)
        $DestinationPath = Join-Path $DestinationFolder $RelativePath

        if (!(Test-Path -Path (Split-Path $DestinationPath))) {
            New-Item -ItemType Directory -Path (Split-Path $DestinationPath) -Force
        }

        Copy-Item $File.FullName -Destination $DestinationPath -Force
        Write-Host "Copying $File"
    }
    else {
        Write-Host "Not copying $File"
    }
}

But as @harrymc noted, if you can use robocopy or the like it might be much simpler.

You can try:

robocopy /S /maxage:20 "c:\temp" "c:\temp1"
1
  • Robocopy worked out perfectly. Thank you. Commented May 26, 2023 at 15:16
1

Don't try to build a tool yourself, when better tools exist in Windows.

Have a look at the robocopy tool that comes with Windows, which has many options and modes of operations.

There are also many free third-party tools that can be found in the Robocopy Alternatives page.

2
  • Robocopy only works where it compares source and destination. The source is over 2 TB of files and there is nothing on the destination. I just need to copy the files changed in the last 20 days and ftp it over to a partner. I don't want to send 2 TB. Commented May 25, 2023 at 15:39
  • 1
    Robocopy and most products should be fast enough if the destination is empty, so there's nothing to compare it to. I don't think that any interpreted script you can write will be faster than a natively-compiled program.
    – harrymc
    Commented May 25, 2023 at 15:48

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .