Thursday, September 13, 2007

In the search for aged files

There has been a lot of questions in the PowerShell news group regarding aged files. To simplify the search process I wrote the "Get-AgedFiles" function. It's simple to use and also pipeline friendly :-)

Get-AgedFiles searches for aged files based on this parameters:


-path, String, starting directory path ,wildcards supported (e.g., c:\scripts\*.ps1)

-age, Integer, file age , default value: 1.

-timePart, String,  can be one of this shortcuts values, default value "d":
    y     = Years
    m    = Months
    d     = Days
    h     = Hours
    mm = Minutes
    s     = seconds
    t     = Ticks

-property, String, The file property for dates comparison , default value "LastWriteTime":
    CreationTime
    CreationTimeUtc
    LastAccessTime
    LastAccessTimeUtc
    LastWriteTime
    LastWriteTimeUtc   

 

-recurse, switch parameter, when declared, performs the search on sub directories.


//TODO:
Add support to get-childitem's include,exclude,filter parameters.

 

 

Usage:

# Get all files from <D:\Backup>, 1 day old (only -path is required) based on <LastWriteTime> property
>> Get-AgedFiles -path "D:\Backup"


# Get all *.bkp files  from <D:\SQLBackup\*.bkp> 10 Days old based on <LastWriteTime> property
>> Get-AgedFiles -path "D:\SQLBackup\*.bkp" -age 10 -timePart d

 

# Get all files, recursively, from <c:\scripts> 6 Months old based on <CreationTime> property
>> Get-AgedFiles -path "c:\scripts" -age 6 -timePart m -property CreationTime -recurse

 

# Get all files from current directory, 7 Days old based on <LastWriteTime> property
# delete all
>> Get-AgedFiles . 7 d | remove-item -whatif

 

# Get all files ,recursively, from current directory, 1 Year old based on <LastWriteTime>
# property, move all to c:\scripts\temp
>> Get-AgedFiles . 1 y -recurse | move-item -destination c:\scripts\temp -whatif

 

The function file is also available for download here.

 

######################################

function Get-AgedFiles{
    param(
        [string]$path=$(throw "needs a path"),           
        [int]$age=1,
        [string]$timePart="TotalDays",
        [string]$property="LastWriteTime",
        [switch]$recurse   
    )

    switch ($timePart){
        "y"    {$timePart="TotalDays"; $age*=365 ; break}
        "m"    {$timePart="TotalDays"; $age*=30 ; break}
        "d"    {$timePart="TotalDays"; break}
        "h"    {$timePart="TotalHours"; break}
        "mm"  {$timePart="TotalMinutes"; break}
        "s"     {$timePart="TotalSeconds"; break}
        "t"     {$timePart="Ticks"; break}
    }

    if($recurse){
        get-childitem $path -recurse | where {
           !$_.psiscontainer -and ((get-date).subtract($_.$property).$timePart -ge $age)
        }   
    } else {
        get-childitem $path | where {
           !$_.psiscontainer -and ((get-date).subtract($_.$property).$timePart -ge $age)
        }           
    }

}

########################

No comments: