Kevin Ray
Kevin Ray

Reputation: 13

Compare current date to date string in a file using powershell

I am writing some PS scripts to log times into a text file, login.txt, using the following code:

$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

This creates an entry in the text file like:

UserName - 01-01-1999

Using Powershell, I want to read the text file, compare the date, 01-01-1999, in the text file to the current date and if more than 30 days difference, extract the UserName to a variable to be used later in the script.

I would really appreciate any hints as to how I could do the following:

  1. Compare the date in the text file to the current date.
  2. If difference is more than 30 days, pick up UserName as a variable.

I would really appreciate any advice.

Upvotes: 0

Views: 3188

Answers (2)

user6811411
user6811411

Reputation:

Checking all dates in the file with the help of a RegEx with named capture groups.

$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
    }
  }
}

Sample output

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

Upvotes: 2

Vivek Kumar Singh
Vivek Kumar Singh

Reputation: 3350

There is a way of doing that using regex (Regular Expressions). I will assume that the username which you get in your text file is .(dot) separated. For example, username looks like john.doe or jason.smith etc. And the entry in your text file looks like john.doe - 01-01-1999 or jason.smith - 02-02-1999. Keeping these things in mind our approach would be -

  1. Using a regex we would get the username and date entry into a single variable.
  2. Next up, we will split the pattern we have got in step 1 into two parts i.e. the username part and the date part.
  3. Next we take the date part and if the difference is more than 30 days, we would take the other part (username) and store it in a variable.

So the code would look something like this -

$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
}

Now you can access the usernames like $array[0], $array[1] and so on. Hope that helps!

NOTE - The regex pattern will change as per the format your usernames are defined. Here is a regex library which might turn out to be helpful.

Upvotes: 0

Related Questions