【问题标题】:In PowerShell, how do I determine if a domain-joined computer is connected to the domain network?在 PowerShell 中,如何确定已加入域的计算机是否连接到域网络?
【发布时间】:2018-01-20 22:43:05
【问题描述】:

在查询 Active Directory 之前,我需要确保计算机实际连接到公司网络(即域网络),并与域控制器建立了安全连接。网络位置感知在幕后执行此操作,并在 GUI 中显示网络配置文件。

如何在 PowerShell 中执行此操作?

【问题讨论】:

    标签: powershell active-directory network-connection


    【解决方案1】:

    这似乎运行良好,并且应该适用于所有版本的 PowerShell:

    function Test-DomainNetworkConnection
    {
        # Returns $true if the computer is attached to a network where it has a secure connection
        # to a domain controller
        # 
        # Returns $false otherwise
    
        # Get operating system  major and minor version
        $strOSVersion = (Get-WmiObject -Query "Select Version from Win32_OperatingSystem").Version
        $arrStrOSVersion = $strOSVersion.Split(".")
        $intOSMajorVersion = [UInt16]$arrStrOSVersion[0]
        if ($arrStrOSVersion.Length -ge 2)
        {
            $intOSMinorVersion = [UInt16]$arrStrOSVersion[1]
        } `
        else
        {
            $intOSMinorVersion = [UInt16]0
        }
    
        # Determine if attached to domain network
        if (($intOSMajorVersion -gt 6) -or (($intOSMajorVersion -eq 6) -and ($intOSMinorVersion -gt 1)))
        {
            # Windows 8 / Windows Server 2012 or Newer
            # First, get all Network Connection Profiles, and filter it down to only those that are domain networks
            $domainNetworks = Get-NetConnectionProfile | Where-Object {$_.NetworkCategory -eq "Domain"}
        } `
        else
        {
            # Windows Vista, Windows Server 2008, Windows 7, or Windows Server 2008 R2
            # (Untested on Windows XP / Windows Server 2003)
            # Get-NetConnectionProfile is not available; need to access the Network List Manager COM object
            # So, we use the Network List Manager COM object to get a list of all network connections
            # Then we get the category of each network connection
            # Categories: 0 = Public; 1 = Private; 2 = Domain; see: https://msdn.microsoft.com/en-us/library/windows/desktop/aa370800(v=vs.85).aspx
    
            $domainNetworks = ([Activator]::CreateInstance([Type]::GetTypeFromCLSID([Guid]"{DCB00C01-570F-4A9B-8D69-199FDBA5723B}"))).GetNetworkConnections() | `
                ForEach-Object {$_.GetNetwork().GetCategory()} | Where-Object {$_ -eq 2}
        }
        return ($domainNetworks -ne $null)
    }
    

    定义此函数后,只需键入:

    Test-DomainNetworkConnection
    

    如果它返回 $true,那么你知道你已经连接到域控制器。

    【讨论】:

    • 这有什么魔力:[Activator]::CreateInstance([Type]::GetTypeFromCLSID([Guid]"{DCB00C01-570F-4A9B-8D69-199FDBA5723B}"))?
    • @Vesper,该代码 sn-p 创建了网络列表管理器 COM 对象的实例。有问题的 GUID 是 NLM COM 对象的 GUID。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-11
    • 1970-01-01
    • 1970-01-01
    • 2013-08-05
    • 2012-07-07
    • 1970-01-01
    • 2017-03-17
    相关资源
    最近更新 更多