PowerShell: Detect Whether Computer is Connected To Domain

# The easy method
$domainConnected=.{
            try {
                [void]::([System.DirectoryServices.ActiveDirectory.Domain]::GetComputerDomain())
                return $true
                }
            catch{
                return $false
                }
}
# The hard way
$otherKnownDnsServers='192.168.500.9000','192.168.500.9001'
$domainConnected=.{
            $regexIpv4 = "\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b"       
            $netdom=netdom query /d:$env:USERDNSDOMAIN DC|?{$_.trim() -notlike "" -and $_ -notmatch '\s'}
            $dcIps=$netdom|%{([System.Net.Dns]::GetHostAddresses($_)).ipaddresstostring}|?{$_ -match $regexIpv4 -and $_ -notmatch "^169."}|sort
            $dcIps+=$otherKnownDnsServers
            $x=Get-WmiObject Win32_NetworkAdapterConfiguration | select DNSServerSearchOrder|out-string
            $x=$x -split '\r?\n'
            $dns=[array]($x | Select-String -Pattern $regexIpv4 -AllMatches).matches.value
	        foreach ($ip in $dns){if ($ip -in $dcIps){return $true}}
            }

Leave a Reply

Your email address will not be published. Required fields are marked *