字符串到日期错误

时间:2017-09-08 13:51:15

标签: powershell datetime

在PowerShell中,我正在尝试将我从文本文件中选择的字符串转换为日期,以便我可以添加或减去日期,小时等。问题是,当我尝试从文本文件转换结果字符串时,我收到以下错误:

Exception calling "ParseExact" with "3" argument(s): "String was not recognized as a valid DateTime."

At line:15 char:5

+     [datetime]::ParseExact($SC4,'HH:mm:ss', $null)
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : FormatException

守则:

Get-Content results2.txt | ForEach-Object{
$splitUp = $_ -split " "
$SC=$splitUp[0] -split " "
$SC2=$splitUp[1] -split " "
$SC3=$SC + $SC2
Write-Host -NoNewline $SC3 | Write-Output $SC4
Write-Host $SC4
$r=[datetime]::ParseExact($SC4,'dd/MM/yyyy HH:mm:ss', $null)
echo $r

}

我读过的文件result2.txt包含以下内容:

09/07/2017 16:35:56 - 2017-09-07 14:55:51,312 [342]
09/07/2017 16:35:56 - 2017-09-07 14:55:51,312 [342]
09/07/2017 16:35:56 - 2017-09-07 14:56:54,918 [305]
09/07/2017 16:35:56 - 2017-09-07 14:58:36,133 [113]

2 个答案:

答案 0 :(得分:1)

问题是因为$SC4是一个空变量。您尝试通过Write-Host的输出管道填充它不起作用(因为Write-Host写入控制台而不是管道)。

整个部分使事情变得复杂并且可以被删除。这在我的测试中工作正常:

Get-Content result2.txt | ForEach-Object {
    $splitUp = $_ -split " "
    $SC=$splitUp[0] -split " "
    $SC2=$splitUp[1] -split " "
    $SC3 = $SC + $SC2
    $r=[datetime]::ParseExact($SC3,'dd/MM/yyyy HH:mm:ss', $null)
    echo $r
}

这是一个较短的解决方案,它使用正则表达式来匹配文件中的第一个日期:

Get-Content result2.txt | ForEach-Object {
    $Check = $_ -Match '^\d{2}/\d{2}/\d{4} \d{2}:\d{2}:\d{2}(?= .*$)'
    If ($Check) { $R=[datetime]::ParseExact($Matches[0],'dd/MM/yyyy HH:mm:ss', $null) }
    Echo $R
}

答案 1 :(得分:0)

其他方法:

Get-Content "c:\temp\test.txt" | ForEach-Object {
    [datetime]::ParseExact(($_ -split " - ")[0],'dd/MM/yyyy HH:mm:ss', $null)
}


#short version
gc "c:\temp\test.txt" |%{[datetime]::ParseExact(($_ -split " - ")[0],'dd/MM/yyyy HH:mm:ss', $null)}