如何从一个文件中获得多个开始时间和结束时间的时差?

时间:2019-05-15 13:25:54

标签: powershell

我的文件包含以下数据,我想使用PowerShell从中获得最大的时差。

STARTTIME:2018-12-01 04:13:15

ENDTIME:2018-12-01 04:17:15

--
--
STARTTIME:2018-12-01 04:11:15

ENDTIME:2018-12-01 04:13:15

--

STARTTIME:2018-12-01 04:10:15

ENDTIME:2018-12-01 04:10:40

我希望输出为00:04:00

1 个答案:

答案 0 :(得分:1)

使用正则表达式选择行和STARTTIME / ENDTIME
设置具有该名称和[datetime]值的变量

## Q:\Test\2019\05\15\SO_56150523.ps1

$FileIn = '.\times.txt'
$RE = [regex]'^(STARTTIME|ENDTIME):(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})'

$Data = (Get-Content $FileIn)| Where-Object {$_ -match $RE}| ForEach-Object{
    Set-Variable -Name $Matches[1] -Value (Get-Date $Matches[2])
    if ($Matches[1] -eq 'ENDTIME'){
        [PSCustomObject]@{
            StartTime = $StartTime
            EndTime   = $EndTime
            Duration  = New-TimeSpan -Start $StartTime -End $EndTime
        }
    }
}
$Data

"`nThe longest duration is {0}" -f ($Data|Sort-Object Duration -Descending)[0].Duration

基于文件times.txt中问题的全文输出样本

> Q:\Test\2019\05\15\SO_56150523.ps1

StartTime           EndTime             Duration
---------           -------             --------
2018-12-01 04:13:15 2018-12-01 04:17:15 00:04:00
2018-12-01 04:11:15 2018-12-01 04:13:15 00:02:00
2018-12-01 04:10:15 2018-12-01 04:10:40 00:00:25

The longest duration is 00:04:00