Home > Active Directory, Powershell, Windows > PowerShell – List users based on Last Logon Time

PowerShell – List users based on Last Logon Time

October 2nd, 2008

I needed an easy way of working out how many active users are on the network in a 60 day period.
I realise I could have done this with DSQUERY/DSGET but I figured it’s high time to learn powershell.. So, this is my first real foray into Windows PowerShell.

To make my life easier I Installed PowerGUI and enabled the Active Directory QAD cmdlets.
The script below searches for all accounts that were logged in within the last 60 days, it only searches in the users OU as specified by the $searchRoot variable.

The output is piped through Measure-Object that counts the number of lines then through Format-Tables that strips all other gunk from Measure-Object and only displays the line count.
$now=get-date
$daysSinceLastLogon=60
$searchRoot=“mash.local/users”

Get-QADUser

-Enabled -SearchRoot $searchRoot -sizeLimit 0 | where {
$_.lastlogontimestamp.value -and (($now-$_.lastlogontimestamp.value).days -le $daysSinceLastLogon
} | Measure-Object -Line | Format-Table Lines

To find unused accounts just change -le to -ge on line 6, this will only give you a count of the unused accounts which is pretty useless. To get a nice table of Users and Last Logon dates change line 7 to look like

} |

Format-Table Name, LastLogon

With full query capabilities and being able to pipe the output to other commands i can see this quickly replacing DSMOD/DSQUERY for me at least.

Wojtek Active Directory, Powershell, Windows ,

  1. No comments yet.
  1. No trackbacks yet.