PowerShell – Get Files Modified In A Certain Date Range And Copy/Delete/Zip…whatever

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
        [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', 

        [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


        $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}
        [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:

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.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s