PowerShell: Disabling and Moving Inactive Users

While this isn’t my cleanest work, it did the job fairly well.

Also, I assume you’ve already added the Active Directory module, I believe command below will add it.

import-module activedirectory

This script will go through an OU, searching it’s contained OU’s, find inactive users then disable and move them into their own ‘Disabled’ sub OU.

This comes in handy when you have a bunch of client sites that are organized and you want to maintain organization.

Foreach ($i in (Get-ADOrganizationalUnit -Filter * -SearchBase "OU=MyOU,DC=mydomain,DC=local" -SearchScope OneLevel | foreach { $_.DistinguishedName })){
    Echo "-------------------------------------------"
    Echo $i
    Echo "-------------------------------------------"
    ForEach ($xx in (Get-ADUser -SearchBase $i -Filter {LastLogonTimeStamp -lt $time -and enabled -eq $true} -Properties LastLogonTimeStamp)){
        [DateTime]::FromFileTime($xx.lastLogonTimestamp)
        Echo "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
        Echo "Disabling User"
        Echo $xx.Name
        Disable-ADAccount -Identity $xx.ObjectGUID
        Echo "Moving User"
        Echo "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
        $DisabledPart1 = "OU=Disabled,"
        $DisabledOU = $DisabledPart1+$i
        Move-ADObject -Identity $xx.ObjectGUID -TargetPath $DisabledOU
    }
    Echo "-------------------------------------------"
}

Below is a script that creates the ‘Disabled’ OUs.

Foreach ($i in (Get-ADOrganizationalUnit -Filter * -SearchBase "OU=MyOU,DC=mydomain,DC=local" -SearchScope OneLevel | foreach { $_.DistinguishedName })){
 echo $i
 New-ADOrganizationalUnit -Name Disabled -Path $i -Description "Disabled Accounts" -PassThru
}

Update


I combined everything into a PowerShell application as seen below and can be downloaded here.

Note: This application will only search through enabled accounts.

Published by

Kevin Herr

System Administrator

Leave a Reply

Your email address will not be published. Required fields are marked *