Private/Get-ADGroupByCN.ps1
function Get-ADGroupByCN { param( [Parameter(Mandatory)][string]$GroupCN, [Parameter(Mandatory)][string[]]$Domains ) $escapedGroup = $GroupCN -replace '([\\*()\0])', { '\{0:x2}' -f [byte][char]$args[0].Value } $filter = "(&(objectCategory=group)(cn=$escapedGroup))" foreach ($domain in $Domains) { try { $dcParts = $domain -split '\.' | ForEach-Object { "DC=$_" } $dcPath = $dcParts -join ',' $gcPath = "GC://$dcPath" Write-Verbose "Searching for group in: $gcPath" $searchRoot = [ADSI]$gcPath $searcher = New-Object DirectoryServices.DirectorySearcher $searcher.SearchRoot = $searchRoot $searcher.SearchScope = 'Subtree' $searcher.PageSize = 100 $searcher.Filter = $filter $searcher.PropertiesToLoad.Add("distinguishedName") | Out-Null $result = $searcher.FindOne() if ($result -and $result.Properties["distinguishedName"].Count -gt 0) { return $result.Properties["distinguishedName"][0] } else { Write-Verbose "Group '$GroupCN' not found in $domain." } } catch { Write-Warning "Error checking group in $domain : $_" } } return $null } |