如何使用powershell从文件中读取时间并对小时执行减法操作

how to read time from file and perform minus operation on hours using powershell

我创建了一个包含 ID 和时间[24 小时格式] 的文本文件,它将在上述时间触发一个操作。

我想同时读取上述值和减去 2 小时。

我试过了,但我不确定如何将输入读取为时间格式(24 小时表示法 HH:MM)并从中减去 2 小时以及 01:30 - 2hr = 23.30(前一个日期)

$lines = Get-Content C:\wamp64\www\schedule_daily_task.txt | Where {$_ -notmatch '^\s+$'} 
foreach ($line in $lines) {
    $fields = $line -split '\s+'
    $id = $fields[0]
    $time = $fields[1] 

    #code here to change the format of $time to time format and perform minus oper 
    #01:30 - 2hr = 23.30 (previous date)
  
 }

对于日期和时间算法,请使用 .Net 的 DateTime class。它有方法 AddHours() ,当传递负值时,减去小时数。计算到昨天的新日期时间非常简单。像这样,

# First, let's get today's date with specific time and minute
$hh = ($fields[1] -split ':')[0]
$mm = ($fields[1] -split ':')[1] 
$dd = get-date -date $(get-date).date -hour $hh -minute $mm

# Add -2 hours
$dd.AddHours(-2)

我会使用 switch -Regex -File 来逐行读取文件并从使用正则表达式后的行中获取值。 优点是这也非常快。

$result = switch -regex -File 'C:\wamp64\www\schedule_daily_task.txt' {
    '^(\d+)\s+(\d{2}:\d{2})' { 
        $id = $Matches[1]
        $h, $m = $Matches[2] -split ':'
        $time = '{0:HH:mm}' -f (Get-Date -Hour $h -Minute $m -Second 0).AddHours(-2)
        # output the id and updated time
        "$id $time"
     }
     default { 
        # output any other line you may have in the file. You can of course 
        # also ignore these if they are unwanted in the output. In that case
        # simply comment out this whole 'default' block
        $_ 
     }
}


# output to (new) file and because of '-PassThru' also on screen
$result | Set-Content -Path 'C:\wamp64\www\schedule_daily_task_minus_2.txt' -PassThru

示例输入文件:

2603961 01:30
1234567 11:59
9876543 23:30

示例输出文件:

2603961 23:30
1234567 09:59
9876543 21:30