简体   繁体   中英

PowerShell: extract timestamp from string

I am brand new to PowerShell and have figured out how to extract a relevant line from a log file:

C:\Documents and Settings\admin\Local Settings\Application Data\Microsoft\SyncToy\2.0\SyncToyLog.log:325:SYNC: 05/22/2012 14:54:55:857: SyncToy run of Profile Backup (C:\Documents and Settings\admin\, H:\Sync\) completed at 5:22/2012 2:54:55 PM.

What I would like to do is extract the first timestamp sans milliseconds (the one that uses 24 hour time) to a variable. Result:

05/22/2012 14:54:55

Any assistance would be appreciated.

One way would be to parse out the date/time string with a regular expression and then convert it to a date/time object:

$line = 'C:\Documents and Settings\admin\Local Settings\Application Data\Microsoft\SyncToy\2.0\SyncToyLog.log:325:SYNC: 05/22/2012 14:54:55:857: SyncToy run of Profile Backup (C:\Documents and Settings\admin\, H:\Sync\) completed at 5:22/2012 2:54:55 PM.'

$dateTimeString = [regex]::Matches($line, '(\d\d/\d\d/\d\d\d\d.+): ')[0].Groups[1].Value

Then convert it to a datetime object:

$provider = New-Object System.Globalization.CultureInfo "en-US"

$dateTime = [datetime]::ParseExact($dateTimeString, 'MM/dd/yyyy HH:mm:ss:fff', $provider)

Now you can display it or store it in a variable however you want:

$dateTime -f 'MM/dd/yyyy HH:mm:ss'

或者干脆:

($line -split ':\s+|:\d{3,}')[2]

with above references, I could do following in my case

I have log file(s) with data lines like below

DefaultSource;Verbose;8;9/5/2016 1:05:19 PM;xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
DefaultSource;Verbose;8;9/5/2016 1:05:20 PM;yyyyyyyyyyyyyyyyyyyyyyyyyyyyyy
DefaultSource;Verbose;8;9/5/2016 1:05:20 PM;zzzzzzzzzzzzzzzzzzzzzzzzzzzz

PS C:\\> $lines = Get-Content "~\\Documents\\FileName.log"

Below line extracts pattern 'd/m/yyyy h:mm:ss [A/P]M' and shows all matching captures

PS C:\\> $lines | %{[regex]::Matches($_,'(\\d+/\\d+/\\d\\d\\d\\d)\\s(\\d+:\\d+:\\d+)\\s([AP]M)')} | Select captures

Get the first value in DateTime Format

PS C:\\> [datetime]$dd = ($lines | %{[regex]::Matches($_,'(\\d+/\\d+/\\d\\d\\d\\d)\\s(\\d+:\\d+:\\d+)\\s([AP]M)')} | Select -First 1 Value).Value

PS C:\\> $dd.GetType().FullName
System.DateTime

PS C:\\> $dd
Monday, September 5, 2016 12:53:20 PM

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM