Home > PowerShell > Get files older than specified time PowerShell

Get files older than specified time PowerShell

April 11th, 2012 Leave a comment Go to comments

Introduction

Its been a bit of a dry spell on the blog recently, in fact the last article I wrote was over 2 months ago now on how you can use a VHD in Windows to make your personal data more portable, this latest article on how to get files older than a specified time in PowerShell follows on from a previous PowerShell article I wrote on how to get the SID of a user or group with PowerShell.

Get files older than a specified time in PowerShell

Almost all Systems Administrators have a requirement to work with files, this blog post details a function I wrote named Get-FilesOlderThan, which is a function I use on an almost daily basis to list files older than a specified time period in PowerShell, once I have retrieved the files I can then carry out a number of actions, such as compressing the files, deleting the files or even sending email alerts.

The code for the Get-FilesOlderThan function can be found below followed by examples on how this function can be used.  For those of you who prefer to download a script that can be used instead of the function, a script can be downloaded from here and used in the same way as the function is used in the examples at the foot of this article.

<#
.SYNOPSIS
Gets files older than a specified age.
.DESCRIPTION
The Get-FilesOlderThan function returns files from within a directory and optionally subdirectories that
are older than a specified period.  The path to begin the search from can be passed as an argument or via
a pipeline.
.INPUTS
System.String
You can pipe a string or an array of strings containing paths to Get-FilesOlderThan       
.PARAMETER Path
Specifies the path the program should begin searching for files from.  Multiple paths can be searched
by passing in an array of paths to search.  If no path is specified the current working directory is used
.PARAMETER Filter
Specifies the file types to be included in the search, by default all file types are included however this
can be filtered by supplying an array of file extensions to include.
.PARAMETER PeriodName
Specifies the name of the period to find files older than.  Accepted values are Seconds, Minutes, Hours,
Days, Months, Years

The PeriodName parameter is mandatory.
.PARAMETER PeriodValue
Specifies the number of ‘X’ to find files older than, where X is the PeriodName.  For example if PeriodName
is set to Hours and PeriodValue is set to 8 the function will return all files older than 8 hours.

The PeriodValue parameter is mandatory.
.PARAMETER Recurse
Specifies that all subfolders of the search path specified should also be searched when searching for files
older than the period specified.
.LINK
http://www.mywinkb.com/Get-files-older-than-specified-time-PowerShell
.EXAMPLE
C:\PS>Get-FilesOlderThan -Path D:\scratch -PeriodName minutes -PeriodValue 5
This command returns all files within the directory D:\scratch which are older that 5 minutes.
.EXAMPLE
C:\PS>Get-FilesOlderThan -Path D:\scratch -PeriodName hours -PeriodValue 10 -Recurse
This command returns all files older than 10 hours from the directory D:\scratch and all subfolders.
.EXAMPLE
C:\PS>Get-FilesOlderThan -Path D:\scratch -Filter *.txt,*.jpg -PeriodName hours -PeriodValue 10 -Recurse
This command returns all .txt and .jpg files older than 10 hours from within the directory D:\scratch
and all subfolders.
.EXAMPLE
C:\PS>Get-Content D:\scratch\directories.txt | Get-FilesOlderThan -PeriodName days -PeriodValue 1
This command reads a list of directories from a .txt file and then lists all files older than 1 day
in each of the folders listed within the file
#>

Function Get-FilesOlderThan {
    [CmdletBinding()]
    [OutputType([Object])]  
    param (
        [parameter(ValueFromPipeline=$true)]
        [string[]] $Path = (Get-Location),
        [parameter()]
        [string[]] $Filter,
        [parameter(Mandatory=$true)]
        [ValidateSet('Seconds','Minutes','Hours','Days','Months','Years')]
        [string] $PeriodName,
        [parameter(Mandatory=$true)]
        [int] $PeriodValue,
        [parameter()]
        [switch] $Recurse = $false
    )
   
    process {
       
        #If one of more of the paths specified does not exist generate an error 
        if ($(test-path $path) -eq $false) {
            write-error "Cannot find the path: $path because it does not exist"
        }
       
        Else {
       
            <# 
            If the recurse switch is not passed get all files in the specified directories older than the period specified, if no directory is specified then
            the current working directory will be used.
            #>
            If ($recurse -eq $false) {
       
                Get-ChildItem -Path $(Join-Path -Path $Path -ChildPath \*) -Include $Filter | Where-Object { $_.LastWriteTime -lt $(get-date).(‘Add’ + $PeriodName).Invoke(-$periodvalue) `
                -and $_.psiscontainer -eq $false } | `
                #Loop through the results and create a hashtable containing the properties to be added to a custom object
                ForEach-Object {
                    $properties = @{
                        Path = $_.Directory
                        Name = $_.Name
                        DateModified = $_.LastWriteTime }
                    #Create and output the custom object    
                    New-Object PSObject -Property $properties | select Path,Name,DateModified
                }               
                 
            } #Close if clause on Recurse conditional
       
            <# 
            If the recurse switch is passed get all files in the specified directories and all subfolders that are older than the period specified, if no directory
            is specified then the current working directory will be used.
            #>  
            Else {
           
                Get-ChildItem  -Path $(Join-Path -Path $Path -ChildPath \*) -Include $Filter -recurse | Where-Object { $_.LastWriteTime -lt $(get-date).(‘Add’ + $PeriodName).Invoke(-$periodvalue) `
                -and $_.psiscontainer -eq $false } | `
                #Loop through the results and create a hashtable containing the properties to be added to a custom object
                ForEach-Object {
                    $properties = @{
                        Path = $_.Directory
                        Name = $_.Name
                        DateModified = $_.LastWriteTime }
                    #Create and output the custom object    
                    New-Object PSObject -Property $properties | select Path,Name,DateModified
                }

            } #Close Else clause on recurse conditional      
        } #Close Else clause on Test-Path conditional
   
    } #End Process block
} #End Fuction

 

The beginning of the code snippet above contains the inline help for the function, which allows you to use the command ‘Get-Help Get-FilesOlderThan’ within your PowerShell console to retrieve help on using the function. Inside the body of the function the Get-ChildItem cmdlet is used to retrieve files based on the parameters passed to the function. The function uses a custom object to output the Path, Name and Last Modified date of the files retrieved by the function.

Examples of how to get files older than a specified time in PowerShell

To use the function shown above to list files older than a specified time in PowerShell you first need to copy the code above and paste this into a Windows PowerShell session before executing it, this will define the function for you and allow you to use Get-FilesOlderThan.  Once you have defined the function you can then use it by calling Get-FilesOlderThan from your PowerShell window, examples on how the function can be used are as follows.

list all .txt files in a directory older than 7 days

Get-FilesOlderThan -Path D:\scratch -PeriodName days -PeriodValue 1

The above command lists all files in the directory D:\scratch with a .txt extension that are older than 7 days, an example output from this command is as follows.

Path          Name                  DateModified      
—-            —-                      ————

D:\scratch output.txt            04/02/2012 19:40:55
D:\scratch schtasks.txt         01/04/2012 19:56:07
D:\scratch scriptoutput.txt    19/02/2012 13:31:07
D:\scratch servers.txt           01/02/2012 18:55:14
D:\scratch tasks.txt              01/02/2012 18:56:05

list all .txt and *.docx files in a directory and all subfolders older than 1 month

Get-FilesOlderThan -Path D:\scratch\ -Filter *.txt,*.docx -PeriodName months -PeriodValue 1 –Recurse

The above command lists all .txt and .docx files in the directory D:\scratch and all subfolders that are older than 1 month, an example of output of this command is listed below.

Path          Name                                     DateModified
—-            —-                                         ————

D:\scratch InstallationNotes.docx           22/02/2012 10:20:55
D:\scratch barcodes.docx                        02/03/2012 13:14:59
D:\scratch New Text Document.txt          09/03/2012 12:54:28
D:\scratch meetingnotes.txt                    01/02/2012 18:56:32
D:\scratch output.txt                               04/02/2012 19:40:55
D:\scratch Remote access.docx               02/02/2012 20:08:20
D:\scratch scriptoutput.txt                       19/02/2012 13:31:07
D:\scratch servers.txt                              01/02/2012 18:55:14
D:\scratch tasks.txt                                 01/02/2012 18:56:05

Review

To review, the function above can be used to list all files of a specified type older than a specified date, examples on how to list files from a single folder and also a folder including subfolders have been provided above, key points on the use of the function are also listed below

  • The –Path parameter contains the path you would like to search for files, if it is not specified then the current working directory is used.
  • The filter parameter requires a comma separated list of file types to include in the output, for example –filter *.txt,*.docx – if no value is provided all files are included
  • The PeriodName parameter contains the time period you would like to use to search for files, accepted values are Seconds,Minutes,Hours,Days,Months,Years
  • The PeriodValue parameter is used in conjunction with the –PeriodName parameter to specify the time period you would like to find files older than, for example –PeriodName Weeks –PeriodValue 2 would search for files older than 2 weeks.

That’s all there is to using the function listed above to get files older than a specified period in PowerShell, remember if you prefer to download a script rather than use a function then a script can be downloaded from here

That’s all for now- I will follow up shortly with a function that can be used to list the defragmentation status of disks on multiple machines.

Categories: PowerShell
  1. cara
    February 1st, 2013 at 05:44 | #1

    I cherch to find on my server, fichier.bak older than 4 days and delete them later

    is that little qulqun give me a hand

    thank you

  1. No trackbacks yet.