Powershell 比较文件中两行的日期、时间戳,并输出最近的日期、日期、时间戳

Powershell 比较文件中两行的日期、时间戳,并输出最近的日期、日期、时间戳,powershell,Powershell,我有下面两行来自两个不同的文件,有日期,时间戳。我需要输出带有最新时间戳的行 一个文件的行: 2000年12月31日星期二17:13:29.83-复制文件 另一个文件内容是: Sun 17/07/1996 12:11:14.84-驾驶员更新 输出必须是 2000年12月31日星期二17:13:29.83-复制文件 如何比较时间戳?要从这些字符串中解析出日期,可以执行以下操作: # get the date and time from the string, remove the dayname

我有下面两行来自两个不同的文件,有日期,时间戳。我需要输出带有最新时间戳的行

一个文件的行:

2000年12月31日星期二17:13:29.83-复制文件

另一个文件内容是:

Sun 17/07/1996 12:11:14.84-驾驶员更新

输出必须是

2000年12月31日星期二17:13:29.83-复制文件


如何比较时间戳?

要从这些字符串中解析出日期,可以执行以下操作:

# get the date and time from the string, remove the dayname as it is incorrect for that date
$dateString = ("Sun 31/12/2000 17:13:29.83 - file copied" -split '-')[0].Substring(4).Trim()
$date1 = [datetime]::ParseExact($dateString, 'dd/MM/yyyy HH:mm:ss.ff', [CultureInfo]"en-US")

# do the same for the date in the second file and call that $date2
然后简单地使用

$theDateYouWant = if ($date1 -gt $date2) { $date1 } else { $date2 }

通过去掉dayname,您可以使用
$null
[cultureinfo]::InvariantCulture
而不是
[cultureinfo]“en-US”
<2000年12月31日是星期日,而不是星期二<代码>1996年7月17日是星期三,不是星期天。这些错误是偶然发生的还是文件中的真实内容?@Theo,我们如何使用3个参数抑制“异常调用”“Parseexact”“:字符串未被识别为有效的日期时间”?这取决于正在解析的日期。你的两个例子前面都有错误的日期名称,因此我发表了评论,这就是为什么我在回答中去掉了它。在这种情况下,您需要检查文件中的任何内容,以及它是否看起来确实是有效的date.fwiw-很高兴替换if语句:
newdatetime(Math.Min(Date1.Ticks,Date2.Ticks))
@LievenKeersmaekers是的,很好。在PowerShell语法中,这将是
$theDateYouWant=[datetime]([math]::Max($date1.Ticks,$date2.Ticks))