20

How can I get the NetBIOS (aka 'short') domain name of the current computer from PowerShell?

$ENV:USERDOMAIN displays the domain of the current user, but I want the domain that the current machine is a member of.

I've discovered you can do it pretty easily in VBScript, but apparently ADSystemInfo isn't very nice to use in PowerShell.

Update

Here's my final solution incorporating the suggestion of using Win32_NTDomain, but filtering to the current machine's domain

$wmiDomain = Get-WmiObject Win32_NTDomain -Filter "DnsForestName = '$( (Get-WmiObject Win32_ComputerSystem).Domain)'"
$domain = $wmiDomain.DomainName
David Gardiner
  • 16,892
  • 20
  • 80
  • 117

11 Answers11

21

In most cases, the default NetBIOS domain name is the leftmost label in the DNS domain name up to the first 15 bytes (NetBIOS names have a limit of 15 bytes). The NetBIOS domain name may be changed during the installation of the Active Directory, but it cannot be changed.

The WIN32_ComputerSystem WMI object gives informations on a Windows computer

PS C:\> Get-WmiObject Win32_ComputerSystem

Domain              : WORKGROUP
Manufacturer        : Hewlett-Packard
Model               : HP EliteBook 8530w (XXXXXXXXX)
Name                : ABCHPP2
PrimaryOwnerName    : ABC
TotalPhysicalMemory : 4190388224

So the domain Name is given by :

PS C:\> (gwmi WIN32_ComputerSystem).Domain

But in domain installation, the DNS name is given. In this case, you can use nbtstat -n command to find the NetBIOS domain name which is displayed like this <DOMAIN><1B>.

The PowerShell Command may be :

nbtstat -n | Select-String -Pattern "^ *(.*) *<1B>.*$" | % {$_ -replace '^ *(.*) *<1B>.*$','$1'}

Here is another way using WMI

PS C:\> (gwmi Win32_NTDomain).DomainName
JPBlanc
  • 70,406
  • 17
  • 130
  • 175
  • I already tried that approach and it doesn't work. The 'Domain' property is not the short/NetBIOS name that I'm after. That contains the full AD domain name – David Gardiner Apr 27 '11 at 07:13
  • I tried this and for mine it shows as <1E> (rather than <1B>) – Mike Shepard Apr 27 '11 at 14:22
  • According to [documentation](http://technet.microsoft.com/en-us/library/cc961857.aspx) it can be <00>, <1B>, <1C>, <1D>, <1E> so you can change the regular expression to "^ *(.*) *<1[BCDE]>.*$" – JPBlanc Apr 27 '11 at 15:02
  • What about Win32_NTDomain WMI object – JPBlanc Apr 27 '11 at 15:35
  • That one looks good in my environment. I like it lots better than the convoluted answer I gave. :-) – Mike Shepard Apr 27 '11 at 16:29
  • 5
    Win32_NTDomain looks like a winner. Note that returns multiple entries, including one for the local computer and probably other trusted domains (if you have any) – David Gardiner Aug 25 '11 at 03:45
11

Use env: to get environment settings through PowerShell

NetBIOS: $env:userdomain

FQDN: $env:userdnsdomain

To see all the values:

dir env:  (no $)
Alperen
  • 3,772
  • 3
  • 27
  • 49
user2027763
  • 119
  • 1
  • 2
6
import-module activedirectory
(Get-ADDomain -Identity (Get-WmiObject Win32_ComputerSystem).Domain).NetBIOSName
Flexo
  • 87,323
  • 22
  • 191
  • 272
Sascha P.
  • 61
  • 1
  • 1
4

From Here

# Retrieve Distinguished Name of current domain.
$Domain = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
$Root = $Domain.GetDirectoryEntry()
$Base = ($Root.distinguishedName)

# Use the NameTranslate object.
$objTrans = New-Object -comObject "NameTranslate"
$objNT = $objTrans.GetType()

# Invoke the Init method to Initialize NameTranslate by locating
# the Global Catalog. Note the constant 3 is ADS_NAME_INITTYPE_GC.
$objNT.InvokeMember("Init", "InvokeMethod", $Null, $objTrans, (3, $Null))

# Use the Set method to specify the Distinguished Name of the current domain.
# Note the constant 1 is ADS_NAME_TYPE_1779.
$objNT.InvokeMember("Set", "InvokeMethod", $Null, $objTrans, (1, "$Base"))

# Use the Get method to retrieve the NetBIOS name of the current domain.
# Note the constant 3 is ADS_NAME_TYPE_NT4.
# The value retrieved includes a trailing backslash.
$strDomain = $objNT.InvokeMember("Get", "InvokeMethod", $Null, $objTrans, 3)
Mike Shepard
  • 17,466
  • 6
  • 51
  • 69
  • FYI I tried this on Windows PowerShell on Windows 10 20H2 and the first line fails with Exception calling "GetCurrentDomain" with "0" argument(s): "Current security context is not associated with an Active Directory domain or forest." – David Gardiner Apr 30 '21 at 04:30
3

OP is after "computer domain" so the answer would be $GetComputerDomain (below) but I will add the $GetUserDomain also for reference.

$GetComputerDomain = ([System.DirectoryServices.ActiveDirectory.Domain]::GetComputerDomain()).Name
$GetUserDomain = ([System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()).Name

I find the wmi (gwmi) option to be extremely slow, especially, when you are querying the Win32_NTDomain class. I have a multi-trusted domain environment and it takes forever when I just need that simple info quick.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • 1
    Sorry, that's not the results I was after. Those both return a full DNS-style domain name. I was after the short/NetBIOS-style domain name. – David Gardiner May 27 '12 at 06:55
2

Use the Active Directory Cmdlet Get-ADDomain:

(Get-ADDomain -Current LocalComputer).NetBIOSName
Jez
  • 620
  • 1
  • 8
  • 13
1

Here is another faster method than Win32_NTDomain, for getting the NetBIOS domain of the computer.

# Get the computer system CIM/WMI
$computersystem = Get-CimInstance Win32_ComputerSystem

# Create a Windows Identity Principal object based on the name and domain in Win32_ComputerSystem
$ComputerPrincipal = [System.Security.Principal.WindowsIdentity]::new("$($computersystem.name)@$($computersystem.domain)")

# Split the NetBIOS name on \ and get the first value which should be the domain
($ComputerPrincipal.Name -split "\\")[0]


# Bonus point, the WindowsIdentity Principal has a bunch of other useful information.
# Like quick enumeration of the groups it's in (but needs to be translated from SID to NTAccount format).
$ComputerPrincipal.Groups.Translate([System.Security.Principal.NTAccount]).value
JMyklebust
  • 11
  • 2
0

The below powershell command works great! I tested after trying various solutions.

If you use the following .Net command:

 [System.Net.Dns]::GetHostByAddress('192.168.1.101').hostname

It works too, but it is using DNS to resolve, in my case, we have WINS setup to support an application that requires it, so can't use it. Below is what I ended up using as part of a script I use to check for WINS registration for each client:

$IPAddress = "<enterIPAddress>" (remove brackets, just enter IP address)

(nbtstat -A $IPAddress | ?{$_ -match '\<00\>  UNIQUE'}).Split()[4]

http://social.technet.microsoft.com/Forums/en-US/f52eb2c7-d55d-4d31-ab4e-09d65d366771/how-to-process-cmd-nbtstat-a-ipaddress-output-and-display-the-computer-name-in-powershell?forum=ITCG

The above link has the thread and conversation.

ez4sheezee
  • 77
  • 1
  • 1
0

Using NetGetJoinInformation and P/Invoke:

Add-Type -MemberDefinition @"
[DllImport("netapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern uint NetApiBufferFree(IntPtr Buffer);
[DllImport("netapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern int NetGetJoinInformation(
  string server,
  out IntPtr NameBuffer,
  out int BufferType);
"@ -Namespace Win32Api -Name NetApi32

function GetDomainName {
  $pNameBuffer = [IntPtr]::Zero
  $joinStatus = 0
  $apiResult = [Win32Api.NetApi32]::NetGetJoinInformation(
    $null,               # lpServer
    [Ref] $pNameBuffer,  # lpNameBuffer
    [Ref] $joinStatus    # BufferType
  )
  if ( $apiResult -eq 0 ) {
    [Runtime.InteropServices.Marshal]::PtrToStringAuto($pNameBuffer)
    [Void] [Win32Api.NetApi32]::NetApiBufferFree($pNameBuffer)
  }
}
Bill_Stewart
  • 22,916
  • 4
  • 51
  • 62
0

This can also be done by using .NET framework (which is much faster than WMI)

PS > [System.Net.NetworkInformation.IPGlobalProperties]::GetIPGlobalProperties()

Will return

HostName      : SurfaceBook
DomainName    : mydomain.com
NodeType      : Hybrid
DhcpScopeName :
IsWinsProxy   : False
Eric Herlitz
  • 25,354
  • 27
  • 113
  • 157
0

Using the ADSystemInfo COM object should work, with no delay from Win32_NTDomain lookup:

$ADSystemInfo = New-Object -ComObject "ADSystemInfo"
$ADSystemInfo.GetType().InvokeMember("DomainShortName", "GetProperty", $null, $ADSystemInfo, $null)

There are other AD-related properties available from this COM object too:

https://learn.microsoft.com/en-us/windows/win32/adsi/iadsadsysteminfo-property-methods

[EDITED - Originally included code for the WinNTSystemInfo COM object instead but a commenter pointed out this only returns the user's short domain - but ADSystemInfo does return the computer's short domain]

Minkus
  • 335
  • 2
  • 13
  • That looks like it's returning the user's domain, not the machine's domain – David Gardiner Apr 30 '21 at 04:28
  • @DavidGardiner Have checked today & the WinNTSystemInfo's DomainName property does return the user's domain, not the machine's domain. But the ADSystemInfo DomainShortName property is as you wanted it to be. I've updated the answer to reflect this. – Minkus May 04 '21 at 16:34