Posted On May 26, 2020

PowerShell: Detect Whether Computer is Connected To Domain

kimconnect 0 comments
blog.KimConnect.com >> Codes >> 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 *

Related Post

Find Empty Directories

$directories="\\FILESERVER01\SHARE01" # Dynamic Credential method 1 $who = whoami if ($who.substring($who.length-2, 2) -eq "-admin"){$username=$who;} else…

Domain Name Records Overview: A-record, MX, DKIM, SPF, SRV

A RECORD (A-host): - What: address record (A-record) specifies the IP address(es) of a given…

PowerShell: Maintain Chocolatey Applications

This current version has some bugs... Review these other codes for some ideas on fixing...…