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