Today a good friend of mine, Damu asked for a function that could copy files from a source to destination based on modified date criteria. Although it could be easily accomplished in the command-line itself, I took upon myself as an exercise to create a wrapper function to do the same in case he wants to use it in multiple ways with simple calls.
Get files modified in a datetime range:
####################### function Get-ChildItemModifiedBetween { [CmdletBinding()] param ( [Parameter(Mandatory=$true, Position=1)] [string] $Path, [Parameter(Mandatory=$true, Position=2)] [DateTime] $ModifiedAfter, [Parameter(Mandatory=$false, Position=3)] [DateTime] $ModifiedBefore = [DateTime]::ParseExact("99991231",'yyyyMMdd', [System.Globalization.CultureInfo]::InvariantCulture), [Parameter(Mandatory=$false, Position=4)] [string] $Filter = '*', [Parameter(Mandatory=$false, Position=5)] [switch] $Recurse = $false ) [string] $fn = $MyInvocation.MyCommand [string] $stepName = "Begin [$fn]" [int] $counter = 1 [int] $choice = 0 try { $stepName = "[$fn]: Get the matches" #-------------------------------------------- Write-Verbose $stepName Get-ChildItem $Path -Recurse: $Recurse -Filter $Filter | Where-Object {$_.mode -notmatch 'd'} | Where-Object {$_.lastwritetime -gt $ModifiedAfter} | Where-Object {$_.lastwritetime -lt $ModifiedBefore} } catch { [Exception]$ex = $_.Exception Write-Error ('Unable to get files modified within given range! Error in step: [{0}] {1}' -f ` $stepName, $ex.Message) } }
Copy qualifying files to a target folder:
Once the matching files are fetched, they just have to be piped to Copy-Item to copy them to any destination.
Get-ChildItemModifiedBetween ` -Path 'F:\Videos\' ` -ModifiedAfter $afterThisDate ` -ModifiedBefore $beforeThisDate ` -Recurse: $true | Copy-Item -Destination C:\Temp\
Thanks to the source
This wrapper is based on code in this blog:
https://rcmtech.wordpress.com/2010/08/12/powershell-find-files-modified-after-a-certain-date/
I recommend using the pipeline and code similar to what is in the above, referenced post. However, if you are compelled to use my function because you might have a lot of references, then you may do so! The code is free and use it as you deem fit.