The "memberof" property is multi-valued property that holds the distinguishedName of the groups.
Your use of the LastLogonTimeStamp won't produce accurate results. While that property is replicated to other DCs, the replication may take between 3 and 14 days. It's precise only on the DC that handled the logon.
You have to check the value on ALL domain controllers in the accounts' domain and use the most recent value on your determination of which accounts to remove.
# Define the OU and group names
$ouName = "OU NAME HERE"
$groupName = "SG_Uitdienst" # must be the sAMAccountname of the group
$groupDN = (Get-ADGroup -Identity $groupName).distinguishedName
if ($null -eq $groupDN) {
Write-Host "Did not find group '$groupName'"
Return
}
# Get the current date
$currentDate = Get-Date
# Get a list of user accounts in the specified OU that are a member of the specified group
Get-ADUser -SearchBase $ouName -Filter { Enabled -eq $false } |
ForEach-Object {
$acct = $_.sAMAccountname
if ($_.memberof -contains $groupDN) {
# Check if the user account has been inactive for longer than 90 days
if (($currentDate - $user.LastLogonTimestamp).Days -gt 90) { # INACCURATE!!!!!
# Delete the user account
Try{
Remove-ADUser -Identity $_.distinguishedName -Confirm:$false -ErrorAction STOP
Write-Host "Deleted user account $($_.SamAccountName)."
}
Catch{
Write-Host "Failed to deleted user account $acct)."
$_
}
}
}
}