Kind of new at this, but I’m currently trying to delete all groups from disabled users besides the primary group for sub OU.
Currently my domain environment looks like this
-company.name.com (domain)
-CompanyName (OU)
-Users (OU) >
-Location 1 (OU)
-Location 2 (OU)
ServiceAcct (OU)
Currently my Powershell script is the following
$searchOU = "OU=CompanyName,DC=company,DC=name,DC=com"
Get-ADGroup -Filter "GroupCategory -eq 'Security'" -SearchBase $searchOU | Sort-Object Name | ForEach-Object {
$group = $_
Get-ADGroupMember -Identity $group | Where-Object { $_.objectClass -eq 'user' } |
Get-ADUser | Where-Object { $_.Enabled -eq $false} | ForEach-Object {
Write-Host "Removing $($_.Name) from $($group.Name)" -Foreground Yellow
Remove-ADGroupMember -Identity $group -Member $_ -Confirm:$false #-whatif
}
}
This runs, but the problem with this is that some disabled users are service accounts and need their security groups, therefore I need to target CompanyName > Users > Location 1 more precisely to avoid messing up service acccounts but when I add the sub OU path (Location 1) and run the following:
$searchOU = "OU=Location1, OU=Users,OU=CompanyName,DC=company,DC=name,DC=com"
Get-ADGroup -Filter "GroupCategory -eq 'Security'" -SearchBase $searchOU | Sort-Object Name | ForEach-Object {
$group = $_
Get-ADGroupMember -Identity $group | Where-Object { $_.objectClass -eq 'user' } |
Get-ADUser | Where-Object { $_.Enabled -eq $false} | ForEach-Object {
Write-Host "Removing $($_.Name) from $($group.Name)" -Foreground Yellow
Remove-ADGroupMember -Identity $group -Member $_ -Confirm:$false #-whatif```
Nothing happens and when I run the sub OU alone:
$searchOU = “OU=Location1,DC=company,DC=name,DC=com”
Get-ADGroup -Filter “GroupCategory -eq ‘Security'” -SearchBase $searchOU | Sort-Object Name | ForEach-Object {
$group = $_
Get-ADGroupMember -Identity $group | Where-Object { $.objectClass -eq ‘user’ } |
Get-ADUser | Where-Object { $.Enabled -eq $false} | ForEach-Object {
Write-Host “Removing $($.Name) from $($group.Name)” -Foreground Yellow
Remove-ADGroupMember -Identity $group -Member $ -Confirm:$false #-whatif
}
}“`
I get the following error
Get-ADGroup : Directory object not found
At line:2 char:1
+ Get-ADGroup -Filter "GroupCategory -eq 'Security'" -SearchBase $searchOU | Sort- ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (:) [Get-ADGroup], ADIdentityNotFoundException
+ FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFou
ndException,Microsoft.ActiveDirectory.Management.Commands.GetADGroup
What am i missing in this code to get to the sub OU?