Tuesday, December 15, 2009

Get Latest File function

Our HR department dumps an employee file that contains the latest listing of employees in the company to the same folder each week. The file contains their employee ID, their Manager, and their manager's employee ID. The following function allows me to get the lastest file from any folder in the last x number of days.
function Get-LatestFile([string]$FilePath, [int]$NumDaysAgo){
    $DateToCompare = (Get-date).AddDays(-$NumDaysAgo)
    return get-childitem $FilePath | where-object {$_.lastwritetime –gt $DateToCompare}
}
Use the function as follows:

$LatestFile = Get-LatestFile "\\server\share\" 7

So basically you supply the folder location and the time frame.  The above command will look for the latest file in the past seven (7) days in the location specified.

No comments:

Post a Comment