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, '\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
i guess i need some fresh eyes to see what i'm missing.
notes:
Just to offer a simpler solution that doesn't require a complex regex:
$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 ' ')
-split, the string-splitting operator is used to split the line into whitespace-separated tokens, and the first two tokens ([0..1]) are joined back with a space.
[datetime] is a culture-invariant way of converting a date-time string into a [datetime] (System.DateTime) instance; this culture-invariant way is based on the InvariantCulture, which is based on the US-English culture.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With