<#Alan Kaplan at VA dot GOV Checks response of DC to required reports, plus DNS query and LDAP Bind version 4.0, 3-1-2018 Revision history at end #> #Requires -version 3 $ProgVer = '4.0' #do not edit #False because we don't need $PS variables $PSDisableSerializationPreference = $False workflow Check-DCWorkflow { param( $DCs2Check, $ignorePing) ForEach ($DC in $DCs2Check) { InlineScript { $computer = $using:DC.Name $IP = $using:DC.IPAddress $isGC = $using:DC.isGC $isDNS = $using:DC.isDNS $ignorePingFailure = $using:ignorePing write-progress -Activity "Launching test thread for:" -Status $computer #Must define here. Variables outside workflow not avaible within $portnames = @{ 7 = 'ICMP Reply' 53 = 'DNS' 88 = 'Kerberos TGT' 135 = 'DCE/RPC' 137 = 'NetBIOS names' 138 = 'NetBIOS datagram' 139 = 'NetBIOS Sessions' 389 = 'LDAP' 445 = 'SMB-GPOs' 464 = 'Kerberos PWD' 636 = 'Secure_LDAP' 3268 = 'GlobalCatalog' 3269 = 'Secure_GC' } add-type -assemblyname System.Windows.Forms #Test-Port function was written by Boe Prox #https://gallery.technet.microsoft.com/scriptcenter/97119ed6-6fb2-446d-98d8-32d823867131/view/Discussions Function Test-Port { <# .SYNOPSIS Tests port on computer. .DESCRIPTION Tests port on computer. .PARAMETER computer Name of server to test the port connection on. .PARAMETER port Port to test .PARAMETER tcp Use tcp port .PARAMETER udp Use udp port .PARAMETER UDPTimeOut Sets a timeout for UDP port query. (In milliseconds, Default is 1000) .PARAMETER TCPTimeOut Sets a timeout for TCP port query. (In milliseconds, Default is 1000) .NOTES Name: Test-Port.ps1 Author: Boe Prox DateCreated: 18Aug2010 List of Ports: http://www.iana.org/assignments/port-numbers To Do: Add capability to run background jobs for each host to shorten the time to scan. .LINK https://boeprox.wordpress.org .EXAMPLE Test-Port -computer 'server' -port 80 Checks port 80 on server 'server' to see if it is listening .EXAMPLE 'server' | Test-Port -port 80 Checks port 80 on server 'server' to see if it is listening .EXAMPLE Test-Port -computer @("server1","server2") -port 80 Checks port 80 on server1 and server2 to see if it is listening .EXAMPLE Test-Port -comp dc1 -port 17 -udp -UDPtimeout 10000 Server : dc1 Port : 17 TypePort : UDP Open : True Notes : "My spelling is Wobbly. It's good spelling but it Wobbles, and the letters get in the wrong places." A. A. Milne (1882-1958) Description ----------- Queries port 17 (qotd) on the UDP port and returns whether port is open or not .EXAMPLE @("server1","server2") | Test-Port -port 80 Checks port 80 on server1 and server2 to see if it is listening .EXAMPLE (Get-Content hosts.txt) | Test-Port -port 80 Checks port 80 on servers in host file to see if it is listening .EXAMPLE Test-Port -computer (Get-Content hosts.txt) -port 80 Checks port 80 on servers in host file to see if it is listening .EXAMPLE Test-Port -computer (Get-Content hosts.txt) -port @(1..59) Checks a range of ports from 1-59 on all servers in the hosts.txt file #> [cmdletbinding( DefaultParameterSetName = '', ConfirmImpact = 'low' )] Param( [Parameter( Mandatory = $True, Position = 0, ParameterSetName = '', ValueFromPipeline = $True)] [array]$computer, [Parameter( Position = 1, Mandatory = $True, ParameterSetName = '')] [array]$port, [Parameter( Mandatory = $False, ParameterSetName = '')] [int]$TCPtimeout = 1000, [Parameter( Mandatory = $False, ParameterSetName = '')] [int]$UDPtimeout = 1000, [Parameter( Mandatory = $False, ParameterSetName = '')] [switch]$TCP, [Parameter( Mandatory = $False, ParameterSetName = '')] [switch]$UDP ) Begin { If (!$tcp -AND !$udp) {$tcp = $True} #Typically you never do this, but in this case I felt it was for the benefit of the function #as any errors will be noted in the output of the report $ErrorActionPreference = "SilentlyContinue" $report = @() } Process { ForEach ($c in $computer) { ForEach ($p in $port) { If ($tcp) { #Create temporary holder $temp = "" | Select Server, Port, TypePort, Open, Notes #Create object for connecting to port on computer $tcpobject = new-Object system.Net.Sockets.TcpClient #Connect to remote machine's port $connect = $tcpobject.BeginConnect($c, $p, $null, $null) #Configure a timeout before quitting $wait = $connect.AsyncWaitHandle.WaitOne($TCPtimeout, $false) #If timeout If (!$wait) { #Close connection $tcpobject.Close() Write-Verbose "Connection Timeout" #Build report $temp.Server = $c $temp.Port = $p $temp.TypePort = "TCP" $temp.Open = $False $temp.Notes = "Connection to Port Timed Out" } Else { $error.Clear() $tcpobject.EndConnect($connect) | out-Null #If error If ($error[0]) { #Begin making error more readable in report [string]$string = ($error[0].exception).message $message = (($string.split(":")[1]).replace('"', "")).TrimStart() $failed = $true } #Close connection $tcpobject.Close() #If unable to query port to due failure If ($failed) { #Build report $temp.Server = $c $temp.Port = $p $temp.TypePort = "TCP" $temp.Open = $False $temp.Notes = "$message" } Else { #Build report $temp.Server = $c $temp.Port = $p $temp.TypePort = "TCP" $temp.Open = $True $temp.Notes = "" } } #Reset failed value $failed = $Null #Merge temp array with report $report += $temp } If ($udp) { #Create temporary holder $temp = "" | Select Server, Port, TypePort, Open, Notes #Create object for connecting to port on computer $udpobject = new-Object system.Net.Sockets.Udpclient #Set a timeout on receiving message $udpobject.client.ReceiveTimeout = $UDPTimeout #Connect to remote machine's port Write-Verbose "Making UDP connection to remote server" $udpobject.Connect("$c", $p) #Sends a message to the host to which you have connected. Write-Verbose "Sending message to remote host" $a = new-object system.text.asciiencoding $byte = $a.GetBytes("$(Get-Date)") [void]$udpobject.Send($byte, $byte.length) #IPEndPoint object will allow us to read datagrams sent from any source. Write-Verbose "Creating remote endpoint" $remoteendpoint = New-Object system.net.ipendpoint([system.net.ipaddress]::Any, 0) Try { #Blocks until a message returns on this socket from a remote host. Write-Verbose "Waiting for message return" $receivebytes = $udpobject.Receive([ref]$remoteendpoint) [string]$returndata = $a.GetString($receivebytes) If ($returndata) { Write-Verbose "Connection Successful" #Build report $temp.Server = $c $temp.Port = $p $temp.TypePort = "UDP" $temp.Open = $True $temp.Notes = $returndata $udpobject.close() } } Catch { If ($Error[0].ToString() -match "\bRespond after a period of time\b") { #Close connection $udpobject.Close() #Make sure that the host is online and not a false positive that it is open If (Test-Connection -comp $c -quiet) { Write-Verbose "Connection Open" #Build report $temp.Server = $c $temp.Port = $p $temp.TypePort = "UDP" $temp.Open = $True $temp.Notes = "" } Else { <# It is possible that the host is not online or that the host is online, but ICMP is blocked by a firewall and this port is actually open. #> Write-Verbose "Host maybe unavailable" #Build report $temp.Server = $c $temp.Port = $p $temp.TypePort = "UDP" $temp.Open = $False $temp.Notes = "Unable to verify if port is open or if host is unavailable." } } ElseIf ($Error[0].ToString() -match "forcibly closed by the remote host" ) { #Close connection $udpobject.Close() Write-Verbose "Connection Timeout" #Build report $temp.Server = $c $temp.Port = $p $temp.TypePort = "UDP" $temp.Open = $False $temp.Notes = "Connection to Port Timed Out" } Else { $udpobject.close() } } #Merge temp array with report $report += $temp } } } } End { #Generate Report $report } } Function Query-DNSServer { Param ( $dc ) $error.Clear() $notes = "Results of NSLookup" $bDNSFailed = $false $retval = nslookup google.com $dc 2>&1 if ([string]$retval -match '\*\*\*') { $bDNSFailed = $true $notes = 'NSLookup of Google.com failed' } [PSCustomObject]@{ Server = $dc Port = '53' TypePort = 'DNSQuery' PortName = 'DNS' Open = !$bDNSFailed Notes = $notes } } Function Test-LDAP { Param ( $dc ) $error.Clear() $Note = "ADSI Bind Succeded" $bLDAPok = $true $retval = [adsi]"LDAP://$DC" if ($error) { $Note = "ADSI Bind Succeded" $bLDAPok = $False $Note = [string]$error[0].Exception.Message } [PSCustomObject]@{ Server = $dc Port = '389' TypePort = 'LDAPTest' PortName = 'LDAP' Open = $bLDAPok Notes = $Note } } Function Check-DC { Param ( $computer, $ignorePingFailure ) $PingReply = [bool](Test-Connection $computer -Count 2 -ErrorAction SilentlyContinue) if ($PingReply -or $IgnorePingFailure) { #You can edit this list #88 TCP, 135 TCP, 139 TCP, 389 BOTH, 445 TCP, 464 BOTH $retVal = Test-Port -computer $computer -port @(88, 135, 389, 445, 464) -TCP $Retval += Test-Port -computer $computer -port @(389, 464) -udp #Optional Secure Ports if ($TestSecurePorts) { $Retval += Test-Port -computer $computer -port @(636, 3689) -udp $Retval += Test-Port -computer $computer -port @(636, 3689) -tcp } if ($isDNS -eq $true) { #53 BOTH, $retVal += Test-Port -computer $computer -port @(53) -TCP $Retval += Test-Port -computer $computer -port @(53) -udp } if ($bNetBIOSCheck -eq $true) { $retVal += Test-Port -computer $computer -port @(139) -TCP $Retval += Test-Port -computer $computer -port @(137, 138) -udp } if ($isGC -eq $True) { $retVal += Test-Port -computer $computer -port @(3268) -TCP } #If DNS port is open run NSLookup to check lookups if (($retval | where {$_.port -eq 53 -and $_.Open -eq $true }).count -eq 2) { $Retval += Query-DNSServer $computer } #If LDAP port is open, do a test bind if (($retval | where {$_.port -eq 389 -and $_.Open -eq $true }).count -eq 2) { $Retval += Test-LDAP $computer } $IP = $using:DC.IPAddress $retval | foreach { $notes = $_.notes [pscustomObject]@{ Server = $computer IPV4Address = $IP Port = $_.port TypePort = $_.TypePort PortName = $portnames.Item($_.Port) Open = $_.Open isGC = $isGC isDNS = $isDNS FailedPing = $bFailedPing Notes = $notes } } } ELSE { #really unlikely if (!($IP)) { Try {$IP = ([System.Net.Dns]::GetHostByName($computer)).AddressList[0].IPAddressToString }Catch {$IP = 'No IP Found'} } $notes = "$computer is offline!" [pscustomObject]@{ Server = $computer IPV4Address = $IP Port = '' TypePort = 'ICMP' PortName = 'Ping' Open = $False isGC = $isGC isDNS = $isDNS Notes = "$computer is offline!" } } } Check-DC $Computer $ignorePingFailure } } } function Get-NetStat { <# .SYNOPSIS This function will get the output of netstat -n and parse the output .DESCRIPTION This function will get the output of netstat -n and parse the output http://www.lazywinadmin.com/2014/08/powershell-parse-this-netstatexe.html Alan changed from -an to -ano to capture PID, and filtered out IPV6 connections #> PROCESS { # Get the output of netstat $data = netstat -ano | where {$_ -notmatch "::"} # Keep only the line with the data (we remove the first lines) $data = $data[4..$data.count] # Each line need to be splitted and get rid of unnecessary spaces foreach ($line in $data) { # Get rid of the first whitespaces, at the beginning of the line $line = $line -replace '^\s+', '' # Split each property on whitespaces block $line = $line -split '\s+' if ($line[4] -ne '*') {$p = $line[4]}ELSE {$p = 999999} # Define the properties $properties = @{ Protocol = $line[0] LocalAddressIP = ($line[1] -split ":")[0] LocalAddressPort = ($line[1] -split ":")[1] ForeignAddressIP = ($line[2] -split ":")[0] ForeignAddressPort = ($line[2] -split ":")[1] State = [string]$line[3] PID = [int]$p } # Output the current line New-Object -TypeName PSObject -Property $properties } } } # =============== script begins ============= $myDom = ([System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()).name #These three are read as the defaults for the form #False skips NetBIOS checks $bNetBIOSCheck = $False #Change to True out to continue where ICMP may be filtered $IgnorePingFailure = $False #Change to False out to skip test of Secure ports $TestSecurePorts = $True Add-Type -assemblyname Microsoft.visualBasic $msg = "This script tests DC port availablilty, DNS and LDAP responses. Get a list of DCs for this domain." #WPF and Powershell #https://foxdeploy.com/2015/04/16/part-ii-deploying-powershell-guis-in-minutes-using-visual-studio/ #Input is from Visual Studio $InputXML = @" "@ $inputXML = $inputXML -replace 'mc:Ignorable="d"','' -replace "x:N",'N' -replace '^