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 Server 2019
Windows Server 2019
A Microsoft server operating system that supports enterprise-level management updated to data storage.
3,984 questions
Active Directory
Active Directory
A set of directory-based technologies included in Windows Server.
6,917 questions
Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,628 questions
PowerShell
PowerShell
A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
2,873 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Rich Matheisen 47,766 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.