Mark Ashley Bell

21 Mar 2023

Copying files modified between two dates with Powershell, retaining original folder structure

I had an email yesterday from someone who had discovered this old post and wanted to know if it was possible to accomplish the same thing, but retain the original folder structure in the destination folder.

That sounded like a nice little puzzle, and it turned out to be a little trickier than I thought... what doesn't, right?

Anyway, with a bit of help from this Stack Overflow answer, here's what I arrived at.

Save this as your cmdlet name of choice, e.g. Copy-Files-Modified-Between-Dates-Recursive.ps1 (or perhaps something snappier):

param (

Get-ChildItem -Path $SourceDirectory -File -Recurse |
Where-Object {
    $_.LastWriteTime `
        -gt (Get-Date $ModifiedAfter) `
        -and $_.LastWriteTime -lt (Get-Date $ModifiedBefore) } |
ForEach-Object {
    $Destination = $_.FullName.Replace(
    New-Item -Type File -Path $Destination -Force
    Copy-Item $_.FullName -Destination $Destination -Force }

As with the previous version, note that this cmdlet supports the standard PS -WhatIf parameter, so you can check the correct files are going to be copied with the correct folder structure, before actually performing the copy.

You can run the command like this:

.\Copy-Files-Modified-Between-Dates-Recursive `
    -SourceDirectory C:\Temp\all `
    -DestinationDirectory C:\Temp\subset `
    -ModifiedAfter '2020-11-01 18:00' `
    -ModifiedBefore '2020-11-02'

Questions or comments? Get in touch @markeebee, or email [Turn On Javascript To View Email Address].

More articles

© Mark Ashley Bell 2023