Check if AD group exists or not

5.2k Views Asked by At

Trying to check if AD group exists or not using below script :

$Path = "LDAP://dc=cmc,dc=com"
$object = "CMC\QTKS-DEP-Admin-Temp"
$type = "Group"

$search = [System.DirectoryServices.DirectorySearcher]$Path
$search.Filter = "(&(name=$object)(objectCategory=$type))"
$Result = $search.FindOne()

IF( $Result -eq $null)
{
Write-Host "Group does not exist"
}
Else 
{   
Write-Host "Group exists"
}

I know something wrong with the LDAP connection string or variables declarations. Or something else. Can someone please correct. The result always shows as "Group does not exist" even if it exists.

1

There are 1 best solutions below

0
On

Got it finally :

$Search = New-Object DirectoryServices.DirectorySearcher
$Search.Filter = '(&(objectCategory=Group)(anr=CMC\QTKS-DEP-Admin-Temp))'
$Search.SearchRoot = 'LDAP://DC=cmc,DC=com'
$Result = $Searcher.FindOne()

IF( $Result -eq $null)
{
Write-Host "Group does not exist"
}
Else 
{              
Write-Host "Group exists"
}