Use PowerShell to Determine the NetBIOS domain name given a specific ADUser

I was writing a script to synchronise AD users to Umbraco using the ActiveDirectory PowerShell snapin today, and I came across a scenario that’s not covered by the properties returned by Get-ADUser.

I had this specific requirement:

Determine the NetBIOS domain name given an AD User object

This is distinct to getting the current domain for the logged-in user, which is a piece of cake:

$env:userdomain

I was iterating through a list of users from Get-ADUser, and needed to know the NetBIOS domain name for each user.

Given the $user variable already exists – for example by doing this:

$user = Get-ADUser -Filter * -ResultSetSize 1

Running the below command will return the NetBIOS name for that user:

(Get-ADDomain (($user.DistinguishedName.Split(",") | ? {$_ -like "DC=*"}) -join ",")).NetBIOSName

I love how you can achieve multi-step procedures in little one-liners like this.

Breaking it down

Split the User DN into an array

# DistinguishedName : CN=Joe Bloggs,OU=Users,OU=Sydney,DC=contoso,DC=com

$user.DistinguishedName.Split(",")

# Becomes:
# CN=Joe Bloggs
# OU=Users
# OU=Sydney
# DC=contoso
# DC=com

Pipe the array to Where-Object (alias: ?) and select only the non-user-parts of the distinguished name

| ? {$_ -like "DC=*"}

# Results in:
# DC=contoso
# DC=com

Join the resulting array back up into a domain distinguished name

-join ","

# Results in:
# DC=contoso,DC=com

Grab the NetBIOSName property returned by Get-ADDomain

(Get-ADDomain <the above code>).NetBIOSName

# Returns:
# CONTOSO

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s