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

PowerShell: Get MD5 Hashing Signature of a File

# Get-MD5-Hash.ps1# Get-FileHash (PowerShell 4.0+) replacement for Windows 2008. Forward-compatible.function getMd5{ param( $file, $md5 =…

PowerShell: List Biggest Files and Folders on a Volume

# listBigFilesAndFolders-v0.01.ps1 # Set variables $parentDirectory="C:\" $depth=4 $topX=10 $excludeDirectories="C:\Windows","C:\Program Files","C:\Program Files (x86)" $clusterSizeOfNetworkShare=8192 # Sanitize…

PowerShell: Obtaining SQL Database Default Paths

# This function returns an array of 3 string values reflecting default Data, Log, and…