Objective:
I am looking at the following objectives via powershell script for active directory disabled user
1. Remove group membership from disabled user, all this users will be in a predefined container in AD.
2. Set Description on disabled user property with removable group membership names for future reference including date and time stamp of removal
3. If any users sets with primary group other than 'domain users' , this needs to be set before removal of group membership of user
4. Since Its recursive task runs via Task Scheduler, previously set description on disabled user shouldn't be removed
I have found the following Microsoft article which is not 100% fancy to my objective.
https://gallery.technet.microsoft.com/scriptcenter/Remove-Disabled-users-from-7e191b6f
With the little knowledge what I have, I made the script to include the Primary Group to set with 'Domain Users' before group removal.
All works as expected for the first run, but with the next run it removes the previously added groups from the description attribute of disabled user. I think it needs to run with IF condition or some other function which does the job and I am not yet well
versed with power-shell scripting.
Your help would be greatly appreciated
Script:
import-module activedirectory
$TargetOU="OU=mytestou,DC=contoso,DC=com"
$users=get-aduser -filter 'enabled -eq $false'-SearchBase $TargetOU -Properties samaccountname,memberof,info,description |select samaccountname, @{n=’MemberOf’; e= { ( $_.memberof | % { (Get-ADObject $_).Name }) -join “,” }}
$date=get-date
Foreach ($user in $users)
{
#Set Description on user property with removable group names for future reference including date and time stamp of removal
Set-ADUser $user.samaccountname -Description "Was a member of :- $($user.memberof)"
# Set Primary Group as Domain Users before removal
$Usersprimarygroup = Get-ADUser -Filter {primaryGroupID -ne 513} -SearchBase $TargetOU
Foreach ($Usersprimarygroup in $Usersprimarygroup) {Set-ADUser -Identity $Usersprimarygroup -Replace @{primaryGroupID=513}}
# Remove From all the Groups
Get-ADGroup -Filter {name -notlike "*domain users*"} | Remove-ADGroupMember -Members $user.samaccountname -Confirm:$False
}
$total = ($users).count
Write-Host "$total accounts have been processed..." -ForegroundColor Green