MyITGuy
2/28/2018 - 12:31 AM

PowerShell: Get-NetBIOSDomainName

Get's the NetBIOS domain name for the current domain context.

function Get-NetBIOSDomainName {
	$RootDSE = [System.DirectoryServices.DirectoryEntry] "LDAP://RootDSE"
	$RootDomain = [System.DirectoryServices.DirectoryEntry] "LDAP://$($RootDSE.configurationNamingContext)"
	$SearchRoot = [System.DirectoryServices.DirectoryEntry] "LDAP://CN=Partitions,$($RootDomain.distinguishedName)"
	$Searcher = New-Object System.DirectoryServices.DirectorySearcher
	$Searcher.SearchRoot = $SearchRoot
	$Searcher.PageSize = 1000
	$Searcher.Filter = "(&(objectcategory=crossref)(netbiosname=*))"

	$hash = @{}
	$Domains = foreach ($Result in $Searcher.FindAll()) {
		foreach ($PropertyName In $Result.Properties.PropertyNames) {
			$PropertyValue = $Result.Properties[$PropertyName]
			if ($PropertyValue -is [System.String]) {
				$PropertyValue = [System.String]$PropertyValue
			} else {
				$PropertyValue = $PropertyValue | % {$_}
			}
			$hash."$([string]$PropertyName)" = $PropertyValue
		}
	    New-Object PSObject -Property $hash
	}

	$DnsDomainName = [DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().Name
	$Domains | ? {$_.dnsroot -eq $DnsDomainName} | Select -ExpandProperty netbiosname
}