【问题标题】:Compare current date to date string in a file using powershell使用 powershell 将当前日期与文件中的日期字符串进行比较
【发布时间】:2018-04-25 00:34:47
【问题描述】:

我正在编写一些 PS 脚本来将时间记录到文本文件 login.txt 中,使用以下代码:

$logdir = "C:\FOLDER"
$logfile = "$logdir\LastLogin.txt"
$user = $env:USERNAME
$date = Get-Date -Format "dd-MM-yyyy"
if (!(Test-Path $logdir)){New-Item -ItemType Directory $logdir}else{}
if (!(Test-Path $logfile)){New-Item $logfile}else{}
if (Get-Content $logfile | Select-String $user -Quiet){write-host "exists"}else{"$user - $date" | Add-Content -path $logfile}
(Get-Content $logfile) | Foreach-Object {$_ -replace "$user.+$", "$user - $date"; } | Set-Content $logfile

这会在文本文件中创建一个条目,例如:

用户名 - 01-01-1999

使用 Powershell,我想读取文本文件,将文本文件中的日期 01-01-1999 与当前日期进行比较,如果相差超过 30 天,将 UserName 提取到变量中以供以后使用在脚本中。

我非常感谢有关如何执行以下操作的任何提示:

  1. 将文本文件中的日期与当前日期进行比较。
  2. 如果相差超过 30 天,则选择 UserName 作为变量。

如果有任何建议,我将不胜感激。

【问题讨论】:

  • 可以减去日期:$diff = $($(Get-Date) - $date_file).Days 为您提供现在之间的天数和一个名为 $date_file 的包含日期的变量。

标签: powershell getdate


【解决方案1】:

借助带有命名捕获组的正则表达式检查文件中的所有日期。

$logdir = "C:\FOLDER"
$logfile = Join-Path $logdir "LastLogin.txt"
$Days = -30
$Expires = (Get-Date).AddDays($Days)

Get-Content $logfile | ForEach-Object {
  if ($_ -match "(?<User>[^ ]+) - (?<LastLogin>[0-9\-]+)") {
    $LastLogin = [datetime]::ParseExact($Matches.LastLogin,"dd-MM-yyyy",$Null)
    if ( $Expires -gt $LastLogin ) {
      "{0} last login {1} is {2:0} days ago" -F $Matches.User, $Matches.LastLogin,
         (New-TimeSpan -Start $LastLogin -End (Get-Date) ).TotalDays
    }
  }
}

样本输出

username last login 31-12-1999 is 6690 days ago

【讨论】:

  • 哇!我不知道你可以命名你的捕获组!太棒了!
  • @HeedfulCrayon 您可以阅读有关该主题的更多信息here
  • 天啊。太感谢了。这完美地工作。我可以将用户名拉入一个变量并继续脚本的其余部分.. 非常感谢。这些 RegEx 看起来很难理解。
  • 要获得 RegEx 的经验,我可以推荐该网站 Regex101.com 它非常详尽地解释了每一步。顺便说一句,最好的坦克是check marks as answer 和/或投票。
  • @LotPings - 这确实很有帮助。比我试过的那个干净多了。感谢您的专业提示! :)
【解决方案2】:

有一种使用regex(正则表达式)的方法。我将假设您在文本文件中获得的username.(dot) 分隔的。例如,用户名看起来像john.doejason.smith 等。文本文件中的条目看起来像john.doe - 01-01-1999jason.smith - 02-02-1999。牢记这些事情,我们的方法是 -

  1. 使用正则表达式,我们可以将usernamedate entry 放入一个变量中。
  2. 接下来,我们将把第 1 步得到的模式分成两部分,即username 部分和date 部分。
  3. 接下来我们获取日期部分,如果差异超过 30 天,我们将获取另一部分 (username) 并将其存储在变量中。

所以代码看起来像这样 -

$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] 等用户名。希望对您有所帮助!

注意 - 正则表达式模式将根据您定义的用户名格式而改变。 Hereregex library,这可能会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-20
    • 1970-01-01
    • 1970-01-01
    • 2021-11-17
    • 2022-01-16
    • 1970-01-01
    • 2017-05-15
    相关资源
    最近更新 更多