Good Afternoon,
I’m trying to add a section to my Active Directory off-boarding script that will remove an AD contact if they have the same name as a disabled user.
Basically, we create AD contacts for all users with their personal email addresses assigned to them. We name the contacts as follows: firstname lastname- personal. So for example: Brandon Hernandez- personal. We have an issue where we are disabling users once they have been terminated, but forgetting to delete their AD contact. So my goals is to add to my off-boarding script a way for it to check if a user is disabled and if they have a corresponding contact, and if yes to delete the contact.
Below is what I have so far:
# If AD user is disabled, delete their corresponding Contact if found.
$DisabledUsers = Get-ADUser -Filter * -SearchBase "OU=Test Disabled Users,DC=Test,DC=local" | Select-Object -ExpandProperty Name
$Contacts = Get-ADObject -LDAPFilter “objectClass=Contact” -SearchBase "OU=Test Contacts,DC=Test,DC=local" | Select-Object -ExpandProperty Name | Foreach-Object { $_ -replace '- personal', '' }
if (Compare-Object $Contacts $DisabledUsers)
{
Get-ADObject -LDAPFilter “objectClass=Contact” -SearchBase "OU=Test Contacts,DC=Test,DC=local" | Remove-ADObject -WhatIf
}
When I run the above code, it just tries to remove all contacts found in the contacts OU.
The result for my $DisabledUsers variable:
Test User2 Brandon Smith Test AccountThe result for my $Contacts variable:
ALAINA TERVALON Brandon Smith Test AccountThe result when I run the above script:
What if: Performing the operation "Remove" on target "CN=ALAINA TERVALON - personal,OU=Test Contacts,DC=Test,DC=local". What if: Performing the operation "Remove" on target "CN=Brandon Smith- personal,OU=Test Contacts,DC=Test,DC=local". What if: Performing the operation "Remove" on target "CN=Test Account- personal,OU=Test Contacts,DC=Test,DC=local".So in order to get it to do what I want, it should only be removing "Brandon Smith" and "Test Account" contacts as those have disabled users with the similar names.
I’m sure I’m over complicating things and I’m missing something simple, but I’m still relatively new to PowerShell and I’m banging my head against the wall on this one.
Thanks for any help I can get on this!
-Brandon