Search code examples
powershellscriptingactive-directorywindows-scripting

Powershell, find users that were disabled in the past 14 days only


I have a powershell script that his output is showing me everything that was disabled for the past 14 days. What i'm looking is to change that this script will run from a specific OU and not the whole DC. I want him to show me only the disabled users for the past 14 days from a specific OU.

The script:

$date = (Get-Date).AddDays(-14)

$disabledUsers = Get-ADObject -Filter 'ObjectClass -eq "User" -and whenChanged -ge $sixMonthsAgo -and UserAccountControl -band 2'

$server = Get-ADDomainController

foreach ($disabledUser in $disabledUsers)
{
    Get-ADReplicationAttributeMetadata $disabledUser -Server $server -Properties UserAccountControl |
    Where-Object { $_.AttributeName -eq 'UserAccountControl' } | Select Object, LastOriginatingChangeTime |
    Where-Object { $_.LastOriginatingChangeTime -gt $date }
}

Solution

  • Using the Filter will make it run quickly $date = (Get-Date).AddDays(-14) get-aduser -filter {Enabled -eq $false -and Modified -ge $date } -Properties Modified | select samaccountname,Modified