gpt4 book ai didi

regex - powershell "ParseExact" "3"参数 : "String was not recognized as a valid DateTime

转载 作者:行者123 更新时间:2023-12-04 15:09:46 37 4
gpt4 key购买 nike

当我尝试解析 IIS 日志文件中的一行并提取该行的日期时间时,出现以下错误

Exception calling "ParseExact" with "3" argument(s): "String was notrecognized as a valid DateTime." At line:9 char:1

  • $dateTime = [datetime]::ParseExact($dateTimeString, 'yyyy-MM-dd HH:mm ...
  •   + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : FormatException

这是我的 powershell 代码:

$line = '2020-12-23 02:01:16.244 -06:00 [Information] 2020-12-23T08:01:16.2446161Z:     [Error] Oracle.ManagedDataAccess.Client.OracleException (0x80004005): Connection request timed out'
$dateTimeString = [regex]::Matches($line, '\d\d\d\d-\d\d-\d\d\s\d\d:\d\d:\d\d')[0].Groups[1].Value
write-host "datetimestr:" $dateTimeString
$provider = New-Object System.Globalization.CultureInfo "en-US"
$dateTime = [datetime]::ParseExact($dateTimeString, 'yyyy-MM-dd HH:mm:ss', $provider)

write-host $dateTime
$dateTime -f 'MM/dd/yyyy HH:mm:ss' | write-host

我想我需要一些新鲜的眼光,看看我错过了什么。

注意事项:

  • 我已经尝试将字符串复制并粘贴到 $line var 中以验证日期时间中没有奇怪的字符
  • 我曾尝试将 .trim 添加到 $line 中,但没有帮助
  • 我还将正则表达式模式缩小为 '\d\d\d-\d\d-\d\d' 并将 parseexact() 缩小为 ($dateTimeString, 'yyyy-MM-dd', $provider)这也无济于事。

最佳答案

只是为了提供一个不需要复杂正则表达式的更简单的解决方案:

$line = '2020-12-23 02:01:16.244 -06:00 [Information] 2020-12-23T08:01:16.2446161Z:     [Error] Oracle.ManagedDataAccess.Client.OracleException (0x80004005): Connection request timed out'

[datetime] ((-split $line)[0..1] -join ' ')
  • -splitstring-splitting operator 用于将行拆分为以空格分隔的标记,前两个标记 ([0..1])用空格连接起来。

  • [datetime] 是一种将日期时间字符串转换为 [datetime] ( System.DateTime ) 实例;这种文化不变的方式基于 InvariantCulture ,它基于美英文化。

关于regex - powershell "ParseExact" "3"参数 : "String was not recognized as a valid DateTime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65430639/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com