R – Active Directory Filter memberof

active-directorypowershellsharepoint

I am trying to get all of the CN's out of active directory in order to populate groups based on that name into Sharepoint Services. I can list the "memberof" section but I can not seem to split it using split(",")

$Dom = 'LDAP://OU=External,OU=Users,OU=HomeOffice,DC=mydoman,DC=com'
$Root = New-Object DirectoryServices.DirectoryEntry $Dom 
$i=0
# Create a selector and start searching from the Root of AD
$selector = New-Object DirectoryServices.DirectorySearcher
$selector.SearchRoot = $root 
$adobj= $selector.findall() |`
where {$_.properties.objectcategory -match "CN=Person"} 
foreach ($person in $adobj){ 
    $prop=$person.properties
    $i++
    Write-host "$($prop.department) - $($prop.sn), $($prop.givenname)"
    Write-host $person.properties["memberof"]
}
"Total $i"

Now I get everything I need, but I need some way to filter only the CN's out…

Best Answer

As a general rule, write-host is not the best way to generate output. Ideally, you want to emit objects out of your function and let PowerShell do the formatting for you. This is the more "pipeline friendly" way of doing things. In this case, if you had a function Get-GroupMembers you could pipe it to something like

Get-Person | ft CN

The trick is creating a new object and adding properties to it, or just emitting the DirectoryServices object you are pulling already. To create a new custom object you can do the following:

$obj = new-object psobject 
$obj | add-member -membertype noteproperty name $PropName -value $valueToStore

People can use your function and pipe it to format-table, format-list, select-object, group-object, sort-object and a variety of other things. Keith Hill's Effective PowerShell has a great chapter on Output that you might find helpful.

There is also an article by Don Jones on using objects instead of text that is quite good as well.