powershellactive-directory

A few groups in my ad are not found by the following script


Import-Module ActiveDirectory

$groups = Get-ADGroup -Filter {(Name -like "F_*" -or Name -like "G_*" -or Name -like "CAX_*")} -Properties Name, GroupCategory | Sort-Object -Property Name

$emptyGroups = @()

foreach ($group in $groups) {
    # Verifica se o grupo é do tipo "Segurança"
    if ($group.GroupCategory -eq 'Security') {
        try {
            $user = Get-ADGroupMember -Identity $group.Name -ErrorAction Stop
            
            if ($user.Count -eq 0) {
                $emptyGroups += $group.Name
            }
        }
        catch {
            Write-Host "Warning: Group '$($group.Name)' could not be found or accessed."
        }
    }
    else {
        Write-Host "Info: Group '$($group.Name)' is not a security group and will be skipped."
    }
}

Write-Host "Empty Groups:"
$emptyGroups | ForEach-Object { Write-Host $_ }

I have this code that searches for groups in my AD. It seems to work well, but some groups are not found, and I don’t know the reason because they clearly exist in my AD. Can you please give me a help?

I'm getting these erros:

Warning: Group 'CAX_BOCAL_265_ORVR_G_L' could not be found or accessed.
Warning: Group 'CAX_GM_GEM_JCCC1_G_E' could not be found or accessed.
Warning: Group 'CAX_GM_GEM_JCCC1_G_L' could not be found or accessed.

Error thrown:

Não é possível localizar um objeto com identidade: 'CAX_BOCAL_265_ORVR_G_L' em: 'DC=myLDAP,DC=com'.


Solution

  • Likely the issue is that Get-ADGroupMember is failing on those groups that have a member that has been deleted however there is no need to use it at all. You can get them using the AD filter directly:

    $getADGroupSplat = @{
        LDAPFilter = '(&(|(name=F_*)(name=G_*)(name=CAX_*))(groupType:1.2.840.113556.1.4.803:=2147483648)(!member=*))'
        Properties = 'Member'
    }
    # Get all Securty groups having Name starting with F_ or G_ or CAX_ that have no members
    $emptyGroups = Get-ADGroup @getADGroupSplat