Handling the userPrincipalName in PowerShell

I dealt with the importance of the userPrincipalName in one of my very early blog postings, dated May 26, 2004: The User Principal Name and You.

While my company has changed, the basic information contained within that post has not changed at all.

I would add one fact: the current Active Directory forest domain is an implied userPrincipalName domain and is not reflected in the list of userPrincipalName domains (also called uPNSuffixes) that are presented in such tools as Active Directory Domains and Trusts. The Active Directory Users and Computer tool is aware of this, and will present it as an option when configuring new user objects.

This PowerShell code handles the addition, reporting, and elimination of UPN suffixes:

#
# userPrincipalName processing routines
#
# Michael B. Smith
# michael@smithcons.com
# April 6, 2009
#
[int] $ADS_PROPERTY_CLEAR	= 1
[int] $ADS_PROPERTY_UPDATE	= 2
[int] $ADS_PROPERTY_APPEND	= 3
[int] $ADS_PROPERTY_DELETE	= 4

function get-ConfigurationPartition
{
	$rootdse  = [ADSI]"LDAP://RootDSE"
	$configNC = $rootdse.ConfigurationNamingContext
	$rootdse  = $null

	$partition = [ADSI]("LDAP://CN=Partitions," + $configNC)

	return $partition
}

function get-UPN
{
	$config = get-ConfigurationPartition
	$suffix = $config.uPNSuffixes
	$config = $null

	return $suffix
}

function test-UPN([string]$upn)
{
	$suffixes = get-UPN

	if (!$suffixes)
	{
		return $false
	}

	if (($suffixes -is [System.String]) -and ($suffixes -eq $upn))
	{
		return $true
	}

	foreach ($suffix in $suffixes)
	{
		if ($suffix -eq $upn)
		{
			return $true
		}
	}

	return $false
}

function new-UPN([string]$upn)
{
	if (test-UPN $upn)
	{
		write-error "$upn already exists"
	}
	else
	{
		$config = get-ConfigurationPartition
		$config.PutEx($ADS_PROPERTY_APPEND, "uPNSuffixes", @($upn))
		$config.SetInfo()
		$config = $null
	}
}

function remove-UPN([string]$upn)
{
	if (test-UPN $upn)
	{
		$config = get-ConfigurationPartition
		$config.PutEx($ADS_PROPERTY_DELETE, "uPNSuffixes", @($upn))
		$config.SetInfo()
		$config = $null
	}
	else
	{
		write-error "$upn doesn't exist"
	}
}

Until next time…

If there are things you would like to see written about, please let me know!


Follow me on twitter: @EssentialExch

Leave a Reply

Your email address will not be published. Required fields are marked *