PowerShell 中计算机的 NetBIOS 域

发布于 2024-11-03 09:15:28 字数 714 浏览 1 评论 0 原文

如何从 PowerShell 获取当前计算机的 NetBIOS(又名“短”)域名?

$ENV:USERDOMAIN 显示当前用户的域,但我想要当前计算机所属的域。

我发现你可以在 VBScript 中很容易地做到这一点,但显然ADSystemInfo 不太好用在 PowerShell 中。

更新

这是我的最终解决方案,其中包含使用 Win32_NTDomain,但过滤到当前机器的域

$wmiDomain = Get-WmiObject Win32_NTDomain -Filter "DnsForestName = '$( (Get-WmiObject Win32_ComputerSystem).Domain)'"
$domain = $wmiDomain.DomainName

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

始终不够 2024-11-10 09:15:28

在大多数情况下,默认 NetBIOS 域名是 DNS 域名中最左边的标签,最多为前 15 个字节(NetBIOS 名称的限制为 15 个字节)。
NetBIOS 域名在 Active Directory 安装过程中可能会更改,但无法更改。

WIN32_ComputerSystem WMI 对象提供 Windows 计算机上的信息,

PS C:\> Get-WmiObject Win32_ComputerSystem

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

因此域名由以下方式给出:

PS C:\> (gwmi WIN32_ComputerSystem).Domain

但在域安装中,给出了 DNS 名称。在这种情况下,您可以使用nbtstat -n命令查找NetBIOS域名,其显示如下<1B>

PowerShell 命令可能是:

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

这是使用 WMI 的另一种方法

PS C:\> (gwmi Win32_NTDomain).DomainName
,'$1'}

这是使用 WMI 的另一种方法


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>.*

Here is another way using WMI

PS C:\> (gwmi Win32_NTDomain).DomainName
,'$1'}

Here is another way using WMI



    
吻风 2024-11-10 09:15:28

获取环境设置

使用 env: 通过 PowerShell NetBIOS

$ env:userdomain FQDN: $env:userdnsdomain

要查看所有值:

dir env:  (no $)

Use env: to get environment settings through PowerShell

NetBIOS: $env:userdomain

FQDN: $env:userdnsdomain

To see all the values:

dir env:  (no $)
聽兲甴掵 2024-11-10 09:15:28
import-module activedirectory
(Get-ADDomain -Identity (Get-WmiObject Win32_ComputerSystem).Domain).NetBIOSName
import-module activedirectory
(Get-ADDomain -Identity (Get-WmiObject Win32_ComputerSystem).Domain).NetBIOSName
戒ㄋ 2024-11-10 09:15:28

来自此处

# 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)

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)
山人契 2024-11-10 09:15:28

OP 在“计算机域”之后,所以答案是 $GetComputerDomain (如下),但我也会添加 $GetUserDomain 以供参考。

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

我发现 wmi (gwmi) 选项非常慢,特别是当您查询 Win32_NTDomain 类时。我有一个多信任的域环境,当我只需要快速获得简单的信息时,它需要很长时间。

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.

才能让你更想念 2024-11-10 09:15:28

使用 Active Directory Cmdlet Get-ADDomain:

(Get-ADDomain -Current LocalComputer).NetBIOSName

Use the Active Directory Cmdlet Get-ADDomain:

(Get-ADDomain -Current LocalComputer).NetBIOSName
金兰素衣 2024-11-10 09:15:28

这是另一种比 Win32_NTDomain 更快的方法,用于获取计算机的 NetBIOS 域。

# 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

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
坦然微笑 2024-11-10 09:15:28

使用 ADSystemInfo COM 对象应该可以工作,不会因 Win32_NTDomain 查找而延迟:

[__ComObject].InvokeMember('DomainShortName', 'GetProperty', $null, (New-Object -ComObject ADSystemInfo), $null)

此 COM 对象还提供其他与 AD 相关的属性:

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

[已编辑 - 已更新使用 ADSystemInfo - 响应 WinNTSystemInfo 仅返回用户短域的评论]

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

[__ComObject].InvokeMember('DomainShortName', 'GetProperty', $null, (New-Object -ComObject 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 - Updated to use ADSystemInfo - in response to a comment that WinNTSystemInfo only returns the user's short domain]

做个少女永远怀春 2024-11-10 09:15:28

使用 NetGetJoinInformation 和 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)
  }
}

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)
  }
}
四叶草在未来唯美盛开 2024-11-10 09:15:28

这也可以通过使用.NET框架来完成(比WMI快得多)

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

将返回

HostName      : SurfaceBook
DomainName    : mydomain.com
NodeType      : Hybrid
DhcpScopeName :
IsWinsProxy   : False

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
水中月 2024-11-10 09:15:28

下面的 powershell 命令效果很好!我在尝试了各种解决方案后进行了测试。

如果您使用以下 .Net 命令:

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

它也可以工作,但它使用 DNS 来解析,在我的例子中,我们有 WINS 设置来支持需要它的应用程序,因此无法使用它。下面是我最终使用的脚本的一部分,我用它来检查每个客户端的 WINS 注册:

$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 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文