-2

I'm working with a log file and I want to filter messages that were added in the last 5 minutes, I don't understand why the [datetime]::ParseExact method returns error on this format

LOG FORMAT

18-08-2021          12:00:00               Debug     127.0.0.1       hello

CODE

$nowTime = (Get-Date).AddMinutes(-5)

Get-Content -Path "" |

Where-Object { $_ -match "^(\d{2}-\d{2}-\d{4}\t\d{2}:\d{2}:\d{2})" } |

Where-Object { [datetime]::ParseExact($matches[1], "dd-MM-yyyy `tHH:mm:ss", $null) -gt $nowTime } |

ForEach-Object {

  Write-Output $_

}

ERROR

"ParseExact" with "3" argument(s): "String was not recognized as a valid DateTime."
Bugs Bunny
  • 365
  • 5
  • 19
  • Because there were slashes in the formatter and dashes in the actual date and you probably have an incorrect number of spaces and/or tabs in between? ``[datetime]::ParseExact("19-08-2021`t12:00:00", "dd-MM-yyyy`tHH:mm:ss", $null)`` – iRon Aug 19 '21 at 07:16
  • @iRon Yeah my bad written the code from memory, updated the code sample, I still can't get any output – Bugs Bunny Aug 19 '21 at 07:32
  • Please, use one of the solutions in [Does there exists a PowerShell Escape function for Special Characters](https://stackoverflow.com/q/68132664/1701026) to paste your *exact* log line into the question (or use a cmdlet like `ConvertTo-Json` to show the actual white spaces). – iRon Aug 19 '21 at 07:39
  • Or simply replace all consecutive white-spaces with a single space: `$DateString = $matches[1] -Replace '\s+', ' '` and use `[datetime]::ParseExact($DateString, "dd-MM-yyyy HH:mm:ss", $null)` – iRon Aug 19 '21 at 07:48
  • @iRon Sadly the escaping didn't help still nothing in output, I have updated the log format to 1:1 of the original – Bugs Bunny Aug 19 '21 at 07:58
  • Please consider rephrasing the subject of your question to better deliver your topic. – Dennis Aug 26 '21 at 19:59

1 Answers1

0

I don't think the delimeter formatting is space + tab in your file?

Changing this section

[datetime]::ParseExact($matches[1], "dd-MM-yyyy `tHH:mm:ss", $null)

to omit the space before `t as below made your example work for me

$nowTime = (Get-Date).AddMinutes(-5)
Get-Content -Path "" |
Where-Object { $_ -match "^(\d{2}-\d{2}-\d{4}\t\d{2}:\d{2}:\d{2})" } |
  Where-Object { 
    [datetime]::ParseExact($matches[1], "dd-MM-yyyy`tHH:mm:ss", $null) -gt $nowTime 
  } |
  ForEach-Object {
    Write-Output $_
  }
Dennis
  • 871
  • 9
  • 29