-3
XYZ Dispatcher Agent 'XYZ' is starting task '12821_1' at Tue Nov 12 01:01:49 2019.

Above is the first line in a log file I want to pull out the "Tue Nov 12 01:01:49 2019" in a variable using Powershell. I have tried using REGEX but facing issues with it. A logfile will always start with this kind of line so I need to pull out the date and time to know the start time of the task using this log.

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
  • For help with your code: *show* your code. Show any error you're getting too. – Ansgar Wiechers Nov 13 '19 at 10:59
  • $paths= get-content "\\somepath\AgentLog_12821_1_12821_1.dsp.log" $some = $paths[0] $dateTimeString = [regex]::Matches($some, '(\w{3}/\w{3}/\d\{2}/\d{2}/\d{2}/\d{2}/\d{4}): ')[0].Groups[1].Value – Powershellbud Nov 13 '19 at 11:01
  • Please [edit] your question. Code in comments is unreadable. – Ansgar Wiechers Nov 13 '19 at 11:13
  • 1
    `$line = $Get-Content "\\somepath\AgentLog_12821_1_12821_1.dsp.log" -First 1`, then `$datetimestring = [regex]::Match($line, '\b\w{3} \w{3} \d{2} \d{2}:\d{2}:\d{2} \d{4}\b').Value` – Wiktor Stribiżew Nov 13 '19 at 11:40

1 Answers1

0

If your files consistently have the format described in your post, you can do the following:

$regex = '\w{3} \w{3} \d{2} \d{2}:\d{2}:\d{2} \d{4}'
$firstline = Get-Content '\\somepath\AgentLog_12821_1_12821_1.dsp.log' -TotalCount 1 |
    Where-Object {$_ -match $regex}
$dateTimeString = $Matches[0]

The $Matches automatic variable is a hash table of values based on the previous successful -match result. It requires a successful match in order to automatically update the variable. You can $null the value.


If you want to capture all date matches in a file (one per line), you can use the following. This will capture all dates in an indexed collection ($dateTimeString).

$regex = '\w{3} \w{3} \d{2} \d{2}:\d{2}:\d{2} \d{4}'
$dateTimeString = (Select-String -Path '\\somepath\AgentLog_12821_1_12821_1.dsp.log' -Pattern $regex).Matches.Value
$dateTimeString[0] # First date
AdminOfThings
  • 23,946
  • 4
  • 17
  • 27