Home > front end >  Handling AD user LastLogonDate & current date in PowerShell
Handling AD user LastLogonDate & current date in PowerShell

Time:10-19

I am trying to get user info based on LastLogondate from AD and figure out how many days since user has logged in based on LastLogonDate and Current Date.

Here is the script

$Result = Get-ADUser -filter {SamAccountName -eq 'username'} -Properties UserPrincipalName, mail, LastLogonDate, Enabled
$CurrentDate = (Get-Date)
Write-Host $Result.LastLogonDate
try
{
$LastLogonDays = ($CurrentDate - $Result.LastLogonDate).Days
Write-Host $LastLogonDays
    $Json = @{
    "UserPrincipalName"= $Result.UserPrincipalName;
    "mail"= $Result.mail;
    "LastLogonDate"= ($Result.LastLogonDate).ToString();
    "days"= $LastLogonDays
    }
    $User = $Json
}
catch{
$Message = $_.Exception.Message
}

$JSONOutput = @{"result"=$User;"error"=$Message} | ConvertTo-Json #-Compress
Write-Output $JSONOutput

I am getting expected result but there is also error captured in log, not able to figure out why/how error is occurring

8/18/2021 4:16:45 AM
61
{
    "error":  "Cannot find an overload for \"op_Subtraction\" and the argument count: \"2\".",
    "result":  {
                   "LastLogonDate":  "8/18/2021 4:16:45 AM",
                   "mail":  "[email protected]",
                   "UserPrincipalName":  "UserPrincipalName",
                   "days":  61
               }
} 

CodePudding user response:

To explain why you're getting that error:

PS > [datetime]::Now - $null
Cannot find an overload for "op_Subtraction" and the argument count: "2".

Which means that, this user or the users before this one, had a $null value on their LastLogonDate property. Note that, I'm saying users before this one because of how you approached your code, the value on the variable $Message is never being cleared and you're always adding it's value here:

$JSONOutput = @{"result"=$User;"error"=$Message}

Now, as an alternative, this is how I personally would approach the code. Note that I'm not using a try { } catch { } block in this case as I don't feel its needed.

$ErrorActionPreference = 'Stop'
$CurrentDate = [datetime]::Now
$userName = 'john.doe'

# UserPrincipalName and Enabled are not needed. Both are default properties returned by Get-ADUser
$Result = Get-ADUser -LDAFilter "(SamAccountName=$userName)" -Properties mail, LastLogonDate

if(-not $Result)
{
    throw "No user found with sAMAccountName $userName"
}

Write-Host $Result.LastLogonDate

$Json = @{
    UserPrincipalName = $Result.UserPrincipalName
    mail = $Result.mail
}

if($Result.LastLogonDate)
{
    $LastLogonDays = ($CurrentDate - $Result.LastLogonDate).Days
    Write-Host $LastLogonDays
    $Json.LastLogonDate = $Result.LastLogonDate.ToString()
    $Json.Days = $LastLogonDays
}
else
{
    $Json.Error = "Null value on LastLogonDate for User {0}" -f $Result.Name 
}

$Json | ConvertTo-Json
  • Related