PowerShell Script to find out Inactive users for 90 days and disable and move them to the disable OU

Oliver Dalugodage 0 Reputation points
2023-02-27T07:21:14.0633333+00:00

Hi Guys,

I want to automate the following process with a PowerShell script in the Domain Controller, Windows Server 2019.1. Find out all the users who have not logged in using the AD account in the last 90 days, disable them, and move them to the disabled OU. I ran the following Powershell script and found out it is not accurate. It even found my account inactive.

I used this script but seems to be inaccurate.

$inactivity = New-TimeSpan -Days 90Search-ADAccount -UsersOnly -AccountInactive -TimeSpan $inactivity 

Please help.

Thank you so much

Windows for business Windows Client for IT Pros Directory services Active Directory
Windows for business Windows Server User experience PowerShell
Windows for business Windows Server User experience Other
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Rich Matheisen 47,901 Reputation points
    2023-02-28T20:45:09.62+00:00

    The Search-ADAccount cmdlet is probably using the lastlogondate to determine when that last interactive logon took place for a user account. The problem with that is that the lastlogondate property is only accurate within a range (typically 3 - 14 days). That's because that property isn't replicated immediately, it's replicated on a random schedule (probably based on how busy replication is within the AD forest).

    The lastlogondate is updated on the DC that handled the logon, but you'd have to know which DC that was to be as accurate as you can. The alternative is to query each DC in the users' AD domain and get the most recent logon from them all.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.