aatanasov
aatanasov

Reputation: 57

How to modify regex for date format?

I got this from /r/sysadmin on Reddit, but the date format is different since the dude is from Europe and he used a Regular Expression, which I am fairly new to using.

The array which is filled using the RegEx as a filter is coming up empty since the RegEx is incorrect and the line where the DateTime format is set is coming up with an error stating that the string is invalid.

I tried changing the DateTime format from dd.MM.yyyy to M.d.yyyy and then matching the RegEx, but it was probably wrong.

# Determine user's last logon time
# The script reads the output of "query.exe user" and parses the date 
# and time returned by it using a regular expression.
# ADJUST: Make sure to change the regular expression to match your date format.
$query = query.exe user $env:username
($user, $logon, $matches) = ($null, $null, $null)

foreach ($line in $query) 
{
    $temp = $line -match '^\>([a-zA-Z0-9-_]+).*((\d{1}\.){1}\d{4}\ \d{2}\:\d{2})$'
}
$user = $matches[1]
$last_logon = $matches[2]

$getdt = (Get-Culture).DateTimeFormat
$DateFormat = $getdt.ShortDatePattern
$TimeFormat = $getdt.ShortTimePattern
$DateTimeFormat = '$DateFormat $TimeFormat'

# This calculates the timespan between NOW and the last time the user logged in

# ADJUST: Make sure the date format matches your locale
$last_logon_duration = (New-TimeSpan –Start ([datetime]::ParseExact($last_logon, `
    'M.d.yyyy HH:mm', $null)) -End (Get-Date))

I am expecting it to put the Username in $user, the DateTime in $last_logon, and for the DateTime format to be recognized as valid.

At Z:\Adrian\Ticket Items\Projects\30 Day reboots\Reboots.ps1:96 char:1
+ $user = $matches[1]
+ ~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : NullArray

Cannot index into a null array.
At Z:\Adrian\Ticket Items\Projects\30 Day reboots\Reboots.ps1:97 char:1
+ $last_logon = $matches[2]
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : NullArray 

Exception calling "ParseExact" with "3" argument(s): "String was not recognized as a valid DateTime."
At Z:\Adrian\Ticket Items\Projects\30 Day reboots\Reboots.ps1:104 char:1
+ $last_logon_duration = (New-TimeSpan –Start ([datetime]::ParseExact($ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : FormatException

Upvotes: 0

Views: 479

Answers (1)

AutomatedChaos
AutomatedChaos

Reputation: 7500

To match M.dd.yyyy you should change the regex to: ^\>([a-zA-Z0-9-_]+).*?(1?\d\.\d\d.\d\d\d\d \d\d\:\d\d)$

See this regex101 entry

I explicitly got rid of the {...} expressions so it makes it more clear to you what it is doing.

Upvotes: 2

Related Questions