NetBIOS domain of computer in PowerShell

后端 未结 9 1873
一个人的身影
一个人的身影 2021-01-04 01: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 th

9条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-04 01:29

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

提交回复
热议问题