powershell - 在子字符串中向日期时间添加小时

标签 powershell

我得到一个带有时间戳记值列表的文件,看起来像这样:

06/14/2018 1:00 1374
06/14/2018 2:00 1316
06/14/2018 3:00 1288

However I need to correct the time stamps by adding four hours to each row. I've been trying something like this:

...
$c = Get-Content $file |
     ForEach-Object { $_.[DateTime]$_.Substring(0, 15).AddHours(4) }
Set-Content $file -Value $c

但是我得到一个错误,即字符串不包含方法AddHours

最佳答案

您的主要问题是operator precedence之一:

 [datetime] $_.substring(0,15).addHours(4)

在应用$_.substring(0,15).addHours(4)强制转换之前先评估[datetime],因此.addHours()是在字符串实例而不是[datetime]实例上调用的,从而导致引用错误。

使用(...)建立所需的优先级:
 ([datetime] $_.substring(0,15)).addHours(4)

日期算术工作后,您需要另外两部分:
  • 以与输入日期
  • 相同的方式格式化重新计算的日期
  • 将输入行的其余部分追加到重新计算的日期

  • $lines = Get-Content $file | ForEach-Object{ 
      (([datetime] $_.substring(0,15)).addHours(4)).ToString('MM/dd/yyyy h:mm') +
        $_.substring(15)
    } 
    
    set-content $file -Value $lines
    

    注意:假设您使用的是15个字符的固定前缀。从每行只有一个小时的数字而没有AM / PM指标的行中,尚不清楚如何处理一天中的所有24小时。

    关于powershell - 在子字符串中向日期时间添加小时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50882159/

    相关文章:

    powershell - 计算目录中PDF文件的数量并输出到.csv

    regex - 可选的非捕获组中的命名捕获组

    powershell - 如何更改参数的抛出消息?

    powershell - 由于复制 S3 存储桶的内容导致 PowerShell 出错

    php - 如何从 powershell 命令行运行 php 脚本?

    powershell - 检查输入 blob 是否存在

    powershell - 尝试使用 Powershell 安装 Sysinternals 时的警告

    windows - 通过 Powershell 或 Batch 将文件从 Windows 转换为 UNIX

    powershell - PowerExplorer.Application com对象和Windows 2012 in Powershell

    powershell - 从所有通讯组中删除所有前雇员