首页 > 解决方案 > 如何修改日期格式的正则表达式?

问题描述

我是从Reddit 上的/r/sysadmin那里得到的,但是日期格式不同,因为这个家伙来自欧洲,而且他使用了正则表达式,我对它还很陌生。

使用 RegEx 作为过滤器填充的数组将变为空,因为 RegEx 不正确,并且设置了 DateTime 格式的行出现错误,指出字符串无效。

我尝试将 DateTime 格式从dd.MM.yyyyto更改为M.d.yyyy 然后匹配 RegEx,但这可能是错误的。

# 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))

我希望它将用户名放入 中$user,将 DateTime 放入 中$last_logon,并将 DateTime 格式识别为有效。

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

标签: regexpowershell

解决方案


要匹配M.dd.yyyy,您应该将正则表达式更改为: ^\>([a-zA-Z0-9-_]+).*?(1?\d\.\d\d.\d\d\d\d \d\d\:\d\d)$

请参阅此 regex101 条目

我明确地去掉了这些{...}表达式,所以它让你更清楚它在做什么。


推荐阅读