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
Works great. Thanks for the tip!
LikeLike
Pingback: Rilevare SamAccountName via Powershell + pre-Windows 2000 Netbios – ServerBay.it - Tutto quello che c'è da Sapere sul mondo Server
This is useful (why cannot NETBIOS domain be part of the user object properties??), but if you are not in the same domain as the account object, even if the domain is in your forest, Get-ADDomain cannot use the Distinguishedname format “DC=contoso,DC=com” as the identity parameter.
But the DNS format for the domain works, so you can join with dots and replace the DC= part to do:
(Get-ADDomain (($user.DistinguishedName.Split(“,”) | ? {$_ -like “DC=*”}) -join “.” -replace “DC=”,””)).NetBiosName
which would provide a DNS-domain string like contoso.com or subdomain.contoso.com, and Get-ADDomain accordingly returns the NetBiosName of any AD domain that DNS resolves for.
LikeLike