Get all AD Users who haven't logged in within 90 days

Does someone know the PowerShell command to see one the last logon of users within the past 90 days in a AD OU, and the last logon before 90 days, also how to output this to a excel spreadsheet?

Thanks

1 Like

Let’s start with the easy one. You can export any array to a spreadsheet by piping the array to the Export-CSV command:

Get-ComputerInfo | Export-Csv -Path C:\ComputerInfo.csv -NoTypeInformation

To do this you will use the Get-ADUser command. Before we do this we will want to create our filter for the OU. We can do all of this like shown below:

$SearchBase = "CN=Users,DC=serveracademy,DC=local"

You can find the search base value by opening Active Directory, enabling Active Directory Advanced features, and opening the properties of the OU you want to search. Go to the Attribute Editor and look for the distinguishedName:

Once you have that information, you can use it like so:

# Search base
$SearchBase = "CN=Users,DC=serveracademy,DC=local"

# Date options
$FixedDate = Get-Date -date "6/29/2021 12:00:00 AM"
$DynamicDate = $(Get-Date).AddDays(-90)

# Create the filter
# Change the -gt (greater than) to -lt (less than) as desired
$Filter = { LastLogonDate -lt $DynamicDate }

# Get all users that match our query
$AllADUsers = Get-ADUser -SearchBase $SearchBase -Filter $Filter -Properties LastLogonDate

# Export to a spreadsheet
$AllADUsers | Export-CSV -Path "C:\AllADUsers.csv" -NoTypeInformation

I added two options for the date - one is a fixed date and the other is a dynamic date just incase you wanted to switch it up and find all users who have or have not logged on since a certain date.

Hope this helps…

Thank you Paul, I will try this.

1 Like