Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

When i'm trying to parse a line in a IIS log file and pulling the datetime on the line, I'm getting the following error

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

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

here is my powershell code:

$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, 'dddd-dd-ddsdd:dd:dd')[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 

i guess i need some fresh eyes to see what i'm missing.

notes:

  • i've tried copying and pasting the string in the $line var to validate there are no strange chars in the datetime
  • i have tried adding .trim to the $line and that didn't help
  • i've also narrowed the regex pattern to 'ddd-dd-dd' and parseexact() to ($dateTimeString, 'yyyy-MM-dd', $provider) and this doesn't help either.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
662 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can use

$dateTimeString = [regex]::Match($line, 'd{4}-dd-ddsdd:dd:dd').Value

Your [regex]::Matches($line, 'dddd-dd-ddsdd:dd:dd')[0].Groups[1].Value code matches a datetime substring into Group 0. You are trying to get Group 1 value by using .Groups[1].Value, but there is no capturing group defined in the pattern.

Note there is no need using Matches that fetches all occurrences in the string since all you need is the first match, which can be done with a mere Match.

Also, repeating d four times in a regex is really redundant, you may use a {4} limiting quantifier.

If you want to only find a match at the start of the string, add ^ at the beginning: '^d{4}-dd-ddsdd:dd:dd'.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...