Powershell 获取最接近给定日期的文件

Powershell 获取最接近给定日期的文件,powershell,get-childitem,Powershell,Get Childitem,我需要一个脚本,这将使我的文件是最接近一个给定的日期,需要一些帮助请 例如: $GivenDate = [datetime]"06/26/2017 10:30" Get-ChildItem $backupDirectory -Filter "*.diff" 输出如下所示: Mode LastWriteTime Length Name

我需要一个脚本,这将使我的文件是最接近一个给定的日期,需要一些帮助请

例如:

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

Get-ChildItem $backupDirectory -Filter "*.diff"
输出如下所示:

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

如何选择与
$givenDate
最接近的文件?

计算
LastWriteTime
属性值与
$givenDate
之间的
时间跨度
,然后按时间跨度的绝对值(持续时间)排序:

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

计算
LastWriteTime
属性值和
$GivenDate
之间的
TimeSpan
,然后根据TimeSpan的绝对值(持续时间)排序:

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

@Mathias R.Jessen溶液的变化(不需要持续时间和时间跨度)


@Mathias R.Jessen溶液的变化(不需要持续时间和时间跨度)

你是在寻找最近的在
$givendate
,之前还是不在乎?你是在寻找最近的在
$givendate
,之前还是不在乎?(持续时间和时间跨度不是必需的)“-这完全取决于他对“最近的”的定义:-(持续时间和时间跨度不是必需的)-这完全取决于他对“最近”的定义:-)