Search code examples
regexpowershelldatetimestamp

Pull out the date and time stamp from notepad using PowerShell


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.


Solution

  • 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