Monday, February 25, 2013

wish (i knew when) you were here

User accounts in Active Directory store information about the last time a user was logged in. How can we use PowerShell to get the number of days since a user last logged on to the domain? A simple way to do this is to use DateTime objects. These guys have some nifty methods that deal very effectively with operations on—well—dates and times.
So what we’re going to do is get a user object’s last logon as a DateTime. The property we’re looking for is
the LastLogonDate property. We’ll also get the current time, and use the DateTime object’s Subtract method to determine the difference between then and now.
$DavesLastLogon = Get-ADUser Dave -Property LastLogonDate | 
        Select-Object -ExpandProperty LastLogonDate
$Now = Get-Date
$DaysSinceLastLogon =  $Now.Subtract($DavesLastLogon).Days
The resulting TimeSpan object has a Days property that we can examine and, voilĂ , that’s how many days have gone by since the user last logged on.
Use the object’s ToString method to get the days, hours, minutes and seconds in a format suitable for reports:
Be seeing you.