有一种方法可以使用
regex
(正则表达式)。我假设
username
你在文本文件中得到的是
.(dot)
分开的。例如,用户名如下所示
john.doe
或
jason.smith
文本文件中的条目如下所示
john.doe - 01-01-1999
或
jason.smith - 02-02-1999
.记住这些,我们的方法是-
-
使用正则表达式,我们可以得到
用户名
和
date entry
转换为单个变量。
-
接下来,我们将把步骤1中得到的模式分为两部分,即
用户名
零件和
date
部分
-
接下来,我们选择日期部分,如果差值超过30天,我们将选择另一部分(
用户名
)并将其存储在变量中。
所以代码看起来像这样-
$arr = @() #defining an array to store the username with date
$pattern = "[a-z]*[.][a-z]*\s[-]\s[\d]{2}[-][\d]{2}[-][\d]{4}" #Regex pattern to match entires like "john.doe - 01-01-1999"
Get-Content $logfile | Foreach {if ([Regex]::IsMatch($_, $pattern)) {
$arr += [Regex]::Match($_, $pattern)
}
}
$arr | Foreach {$_.Value} #Storing the matched pattern in $arr
$UserNamewithDate = $arr.value -split ('\s[-]\s') #step 2 - Storing the username and date into a variable.
$array = @() #Defining the array that would store the final usernames based on the time difference.
for($i = 1; $i -lt $UserNamewithDate.Length;)
{
$datepart = [Datetime]$UserNamewithDate[$i] #Casting the date part to [datetime] format
$CurrentDate = Get-Date
$diff = $CurrentDate - $datepart
if ($diff.Days -gt 30)
{
$array += $UserNamewithDate[$i -1] #If the difference between current date and the date received from the log is greater than 30 days, then store the corresponding username in $array
}
$i = $i + 2
}
现在您可以访问以下用户名
$array[0]
,则,
$array[1]
等等希望有帮助!
注意-regex模式将根据定义的用户名格式进行更改。
Here
是一个
regex library
这可能会有帮助。