supportth
supportth

Reputation: 29

Get file which is closest to a given date

I need a script which will get me the file which is closest to a given date, and need some help please.

For example:

$GivenDate = [datetime]"06/26/2017 10:30"

Get-ChildItem $backupDirectory -Filter "*.diff"

Output looks like this:

Mode                LastWriteTime         Length Name                                                                                                                                                       
-a----       25.06.2017     15:30         506368 db1_backup_2017_06_25_153001_5520722.diff                                                                                                               
-a----       26.06.2017      7:30        1597952 db1_backup_2017_06_26_073001_6387310.diff                                                                                                               
-a----       26.06.2017      9:30         675840 db1_backup_2017_06_26_093001_6217913.diff                                                                                                               
-a----       26.06.2017     11:30         657408 db1_backup_2017_06_26_113001_1234104.diff                                                                                                               
-a----       26.06.2017     13:30         675328 db1_backup_2017_06_26_133000_9901392.diff                                                                                                               
-a----       26.06.2017     15:30         673792 db1_backup_2017_06_26_153001_5430241.diff

How can I select the file that is closest to to $givenDate?

Upvotes: 1

Views: 708

Answers (2)

Esperento57
Esperento57

Reputation: 17462

variation of @Mathias R. Jessen solution (duration and timespan are not necessary)

Get-ChildItem $backupDirectory -file -Filter *.diff  | sort {($GivenDate - $_.LastWriteTime)} | Select -First 1

Upvotes: 0

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174485

Calculate a TimeSpan between the LastWriteTime property value and your $GivenDate, then sort on the absolute value (the duration) of the timespan:

$Closest = Get-ChildItem $backupDirectory -Filter *.diff |Sort {(New-TimeSpan $GivenDate $_.LastWriteTime).Duration()} |Select -First 1

Upvotes: 4

Related Questions