07 Nov 2020
Copying files modified between two dates with Powershell
I've recently had the need to copy a subset of files modified between two dates, from a folder containing many thousands. Powershell makes this quite easy, but it took a little bit of figuring out, so I thought I'd share it!
I have this saved as Copy-Files-Modified-Between-Dates.ps1
:
[CmdletBinding(SupportsShouldProcess=$true)]
param (
[Parameter(Mandatory=$true)][string]$SourceDirectory,
[Parameter(Mandatory=$true)][string]$DestinationDirectory,
[Parameter(Mandatory=$true)][string]$ModifiedAfter,
[Parameter(Mandatory=$true)][string]$ModifiedBefore
)
Get-ChildItem -Path $SourceDirectory |
Where-Object {
$_.LastWriteTime `
-gt (Get-Date $ModifiedAfter) `
-and $_.LastWriteTime -lt (Get-Date $ModifiedBefore) } |
ForEach-Object { $_ | Copy-Item -Destination $DestinationDirectory }
Note that this cmdlet supports the standard PS -WhatIf
parameter, so you can check the correct files are going to be copied before actually performing the copy.
You can run the command like this:
.\Copy-Files-Modified-Between-Dates `
-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