CHunky Universe of Vigourous Astonishing SHarepoint :)

Tag Archives: Active Directory

Remove protected Organizational Units from AD

To remove a protected OU, go to ADUC (Active Directory Users and Computers), select the domain and enable “Advanced Features” in View. When Advanced Features are enabled, just right click you OU go to Properties -> Object and uncheck “Protect against accidential deletion”.

Disable Advanced Features after that.

By the way. When Advanced Features are enabled you can even see the distinguished Name of objects directly in ADUC UI.

Adding organizational units to AD through powershell

Want to create some organizational structure in AD, I suppose it is specifically useful in a development environment, well the best solution is powershell then. Mastering Powershell by and by Niklas Goude provide examples how to do this.

$domain = [ADSI]""
$ou = $domain.Create("organizationalUnit", "OU=Administration")

Be sure you write “organizationalUnit” in lower case. Otherwise you’ll get “Exception calling “SetInfo” with “0” argument(s): “The specified directory service attribute or value does not exist” when you invoke $ou.setinfo().

If you want to create an OU under another OU, just create $domain and specify the location:

$domain = [ADSI]"OU=Administration, dc=takana, dc=local"
$company = $domain.Create("organizationalUnit", "OU=Accounting")
To save some other properties:
<pre>$ou.put("Description", "this is a dummy ou")

Update 2013-12-10

In PowerShell V3 you have a built-in cmdlet for doing that once you add the Active Directory role in your server. It simple as that:

New-ADOrganizationalUnit "Accounting" -Path "dc=takana, dc=local"

Find the current Active Directory Domain

While working with Active Directory within SharePoint we probably don’t need to specify the domain or the root container. We can the current values. Here is a simple method from a console application just to demonstrate:

internal static void GetDomain()
	var context = new DirectoryContext(DirectoryContextType.Domain);
	var domain = Domain.GetDomain(context);
	Console.WriteLine("Full domain:");
	Console.WriteLine(domain.Name); //takana.local
	Console.WriteLine("root container");
	var parts = domain.Name.Split(new[] {"."}, StringSplitOptions.RemoveEmptyEntries);
	var dcParts = parts.Select(n => "dc=" + n).ToArray();
	var d = string.Join(",", dcParts); //dc=takana, dc=local

First we get get the full domain, then we split and join them again.

Check if a user is in a OU

To get all users from an AD group is very simple:

groupName = "an_ad_group";
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
GroupPrincipal grp = GroupPrincipal.FindByIdentity(ctx, IdentityType.Name, groupName);
var principals = grp.GetMembers(true);

But what about an OU? There is no OrganizationUnitPrincipal… Well, there is a solution: to instantiate a context for your OU:

So if you want to check if a user in a OU:

internal static bool IsUserInOu(string ou, string name)
	var domain = "takana.local";
	var container = string.Format("OU={0}, DC=takana, DC=local", ou);
	var ctx = new PrincipalContext(ContextType.Domain, domain, container);
	var up = new UserPrincipal(ctx);
	var ps = new PrincipalSearcher(up);

	var results = ps.FindAll();
	return results.Any(p => p.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase));

To avoid hardcoding domain and root container, we can retrieve the current domain.

Powershell scripts for AD

A tip for all who want to administer AD with powershell: Idera Powershell scripts. Just sign up and get the free scripts for AD, SQL, Exchange and Sharepoint.

I personally prefer to user modules, so I change the file extension from ps1 to psm1 and then I can use import functions as modules. Here is a simple example for creating for domain users:

import-module .\New-IADUser1.psm1
function Add-User($name) {
    New-IADUser -Name $name 
         -sAMAccountname $name 
         -ParentContainer 'CN=Users, DC=contoso, DC=com' 
         -Password 'SvenskaAkademien1786' 
         -EnableAccount -PasswordNeverExpires
Add-User "user01"
Add-User "user02"
Add-User "user03"
Add-User "user04"
update 2012-03-15: nice script from Ryan

Ryan Dennis has created a very handy script for creating random users.

In PowerShell v3.0 there is a cmdlet for creating users: New-ADUser. So the function above can be rewritten like that:

Import-Module ActiveDirectory -ErrorAction SilentlyContinue
function Add-User($name) {
    $password = ConvertTo-SecureString 'SvenskaAkademien1786' -AsPlainText -Force
    New-ADUser -Name $name 
         -sAMAccountname $name 
         -Path 'CN=Users, DC=contoso, DC=com' 
         -AccountPassword $password
         -Enabled $true
         -PasswordNeverExpires $true
Add-User "user01"
Add-User "user02"
Add-User "user03"
Add-User "user04"

Get Distinguished Name for a user

To get the distinguished name for a user, it isn’t enough to get an SPUser object. The distinguished name is the unique string for identifying a user in Active Directory (eg. CN=BeforeDAfter,OU=Test,DC=North America,DC=Fabrikam,DC=COM) Even using UserProfile object is not that clear. The distinguished name can be found in a property which can be retrieved with brackets:

public static string GetDistinguishedName(string login)
   var dn = "";
   UserProfile up;
   using (var site = new SPSite("http://dev"))
      var serviceContext = SPServiceContext.GetContext(site);
      var upm = new UserProfileManager(serviceContext);
      var exists = upm.UserExists(login);
      if (!exists)
      if (exists)
         up = upm.GetUserProfile(login);
         dn = up[PropertyConstants.DistinguishedName].Value.ToString();
   return dn;

The code is simplified and doesn’t contain any error handling. And a better handling of upm.UserExists must be implemented: If upm.CreateUserProfile(login) runs, it doesn’t make it so quickly and the next step won’t run (upm.GetUserProfile).

If you are not working in SP Context, you can see the distinguished name for a user in Powershell:

import-module activedirectory
$u = get-aduser administrator

Retrieve information from AD

Here is a a link you can start with.

To test AD, install AD. Then we canplay with it. Take a look those examples, too.

PrincipalSearcher vs. DirectorySearcher

What is the difference?


Here are two examples (one for PrincipalSearcher and the other for DirectorySearcher) to retrieve users from an OU:

internal static void ListPrincipalsFromOu()
	using(var ctx = new PrincipalContext(ContextType.Domain, "takana.local", "OU=SOME_OU ,DC=takana, DC=local"))
		using (var up = new UserPrincipal(ctx))
			using (var ps = new PrincipalSearcher(up))
				using (var res = ps.FindAll())
					foreach (var p in res)

internal static void ListAdEntriesFromOu()
	const string property = "sAMAccountName";
	var ldapcon = new DirectoryEntry("takana.local") {
		Path = "LDAP://OU=SOME_OU,DC=takana,DC=local"
	var search = new DirectorySearcher(ldapcon);

	using (var results = search.FindAll())
		foreach (System.DirectoryServices.SearchResult result in results)
			using (var entry = result.GetDirectoryEntry())
				if (entry.Properties[property].Count > 0)
Daniel Chronlund Cloud Tech Blog

News, tips and thoughts for Microsoft cloud fans

Вула Чăвашла

VulaCV - Чăвашла вулаттаракан сайт

Discovering SharePoint

And going crazy doing it

Bram de Jager - Architect, Speaker, Author

Microsoft 365, SharePoint and Azure

SharePoint Dragons

Nikander & Margriet on SharePoint

Mai Omar Desouki

PFE @ Microsoft

Cameron Dwyer

Office 365, SharePoint, Azure, OnePlace Solutions & Life's Other Little Wonders


Me and My doings!

Share SharePoint Points !

By Mohit Vashishtha

Jimmy Janlén "Den Scrummande Konsulten"

Erfarenheter, synpunkter och raljerande om Scrum från Jimmy Janlén

Aryan Nava

DevOps, Cloud and Blockchain Consultant


SharePoint for everyone


Ryan Dennis is a SharePoint Solution Architect with a passion for SharePoint and PowerShell

SharePoint 2020

The Vision for a Future of Clarity

Aharoni in Unicode

Treacle tarts for great justice

... And All That JS

JavaScript, Web Apps and SharePoint


Mostly what I know and share about...