首页 > 解决方案 > Powershell 日期时间过滤器未使用正确的 ShortDate 模式

问题描述

我正在尝试在 Get-ChildItem 函数上过滤 LastWriteTime,但是当我尝试使用英国日期进行过滤时,它会失败,因为它不是美国格式。

当我运行时,(Get-Culture).DateTimeFormat.ShortDatePattern我收到dd/MM/yyy正确的格式。

但是,当我执行 powershell 过滤器语句时:-

GCI 'C:\ | ?{$_.LastWriteTime -ge '21/01/2018'}

我收到以下信息:-

Cannot convert value "21/01/2018" to type "System.DateTime". Error: "String was not recognized as a valid DateTime."

但是,如果我将日期更改为01/21/2018我收到正确的结果。

我尝试使用$_.LastWriteTime.ToString('dd-MM-yyyy') -ge '01[![enter image description here][1]][1]/01/2018'无法正常工作的,因为它从 2017 年返回日期。

PS1 PS2

标签: powershell

解决方案


首先将您的日期字符串转换为日期对象:

$date = get-date '21/01/2018'
gci C:\ | ? {$_.LastWriteTime -ge $date }

推荐阅读