我是从Reddit上的/r/sysadmin那里获得的,但日期格式却有所不同,因为该家伙来自欧洲,并且他使用了一个正则表达式,这对我来说是个新手。
使用RegEx作为过滤器填充的数组显示为空,因为RegEx不正确,并且设置DateTime格式的行显示一条错误,指出该字符串无效。
我尝试将DateTime格式从dd.MM.yyyy
更改为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
答案 0 :(得分:2)
要匹配M.dd.yyyy
,您应将正则表达式更改为:
^\>([a-zA-Z0-9-_]+).*?(1?\d\.\d\d.\d\d\d\d \d\d\:\d\d)$
我明确地摆脱了{...}
表达式,因此它使您更清楚自己在做什么。