There are a number of answers to this using DirectoryEntry but nothing relating to the AccountManagement classes.
Is there a way I can use AccountManagement to get a list of OU?
There are a number of answers to this using DirectoryEntry but nothing relating to the AccountManagement classes.
Is there a way I can use AccountManagement to get a list of OU?
Personally, I think "DirectoryEntry" is probably the way to go.
But this link suggests you can use PrincipalContext:
Get Groups From OU using DirectoryServices.AccountManagement
Old question but still, i just had to solve it so i'll share what i found : You can extend the Principal Object to any ActiveDirectory Object (search Principal Extensions in learn.microsoft.com) For exemple :
[DirectoryRdnPrefix("OU")]
[DirectoryObjectClass("organizationalUnit")]
public class OuPrincipal : GroupPrincipal
{
public OuPrincipal(PrincipalContext pc) : base(pc)
{
}
OuPrincipalSearchFilter searchFilter;
public OuPrincipalSearchFilter AdvancedSearchFilter
{
get
{
if ( null == searchFilter )
searchFilter = new OuPrincipalSearchFilter(this);
return searchFilter;
}
}
public object[] GetAttribute(string attribute)
{
return (ExtensionGet(attribute));
}
[DirectoryProperty("st")]
public string State
{
get
{
if (ExtensionGet("st").Length != 1)
return null;
return (string)ExtensionGet("st")[0];
}
}
I just needed a list of Ous With something in the "State" property so i needed to extend an advancedFilterSet
public class OuPrincipalSearchFilter : AdvancedFilters
{
public OuPrincipalSearchFilter(Principal p) : base(p){}
public void testState(string value)
{
this.AdvancedFilterSet("st", value, typeof(string), MatchType.Equals);
}
}
And then :
var test = new OuPrincipal(pc);
test.AdvancedSearchFilter.testState("*");
PrincipalSearcher ps = new PrincipalSearcher(test);
var rslts = ps.FindAll();
foreach(OuPrincipal ou in rslts)
{
Console.WriteLine("OU "+ou.Name+" : "+ou.State+" ("+ou.Description+")");
}
I hope it helps someone (or myself next time i forget...). i used this github repository for inspiration.