Skip to content

Instantly share code, notes, and snippets.

@henno
Last active December 4, 2024 08:48
Show Gist options
  • Save henno/f512204c7f0b284198424a31c0ef9132 to your computer and use it in GitHub Desktop.
Save henno/f512204c7f0b284198424a31c0ef9132 to your computer and use it in GitHub Desktop.
Windows Network Monitoring Script
$ErrorActionPreference = "SilentlyContinue"
# Variables for easy modification
# Adapter names (provide one or more adapter names)
$AdapterNames = @("Ethernet")
# Examples:
# $AdapterNames = @("Ethernet", "Wi-Fi")
# ICMP Ping destinations (provide one or more IP addresses)
$AdditionalPingDestinations = @("8.8.8.8")
# Examples:
# $AdditionalPingDestinations = @("8.8.8.8", "1.1.1.1")
# TCP connectivity tests (provide one or more "hostname:port" entries)
$TcpTestHosts = @()
# Examples:
# $TcpTestHosts = @("example.com:80", "example.net:3389")
# DNS hostnames to resolve (provide one or more hostnames)
$DnsHostnames = @("www.google.com")
# Examples:
# $DnsHostnames = @("www.google.com", "www.google.ee")
# Log file path
$logFilePath = ".\LogNetworkStatus.txt"
# Show current configuration
Write-Host "Current Configuration:"
Write-Host "Adapter Names:" ($AdapterNames -join ", ")
Write-Host "Additional Ping Destinations:" ($AdditionalPingDestinations -join ", ")
Write-Host "TCP Test Hosts:" ($TcpTestHosts -join ", ")
Write-Host "DNS Hostnames:" ($DnsHostnames -join ", ")
Write-Host "Log File Path:" $logFilePath
Write-Host ""
# Validate Adapter Names
if ($AdapterNames.Count -gt 0) {
$AvailableAdapters = Get-NetAdapter | Select-Object -ExpandProperty Name
$InvalidAdapters = $AdapterNames | Where-Object { $_ -notin $AvailableAdapters }
if ($InvalidAdapters.Count -gt 0) {
Write-Host "Error: The following adapter(s) do not exist on this system:" -ForegroundColor Red
foreach ($Adapter in $InvalidAdapters) {
Write-Host " - $Adapter" -ForegroundColor Red
}
Write-Host "Please check the adapter names and try again." -ForegroundColor Red
exit
}
}
while ($true) {
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
# Initialize variables
$AdapterResults = @()
$PingDestinationsCurrent = @()
$LatencyResults = @{}
$DnsResults = @{}
$TcpTestResults = @()
# Process Network Adapters
if ($AdapterNames.Count -gt 0) {
foreach ($AdapterName in $AdapterNames) {
$AdapterConfig = Get-NetIPConfiguration -InterfaceAlias $AdapterName
$AdapterInfo = [PSCustomObject]@{
Name = $AdapterName
IPAddress = "Not Connected"
Gateway = "No Gateway"
}
if ($AdapterConfig -and $AdapterConfig.IPv4Address) {
$AdapterInfo.IPAddress = $AdapterConfig.IPv4Address.IPAddress
if ($AdapterConfig.IPv4DefaultGateway) {
$AdapterInfo.Gateway = $AdapterConfig.IPv4DefaultGateway.NextHop
# Add gateway to ping destinations
if ($AdapterInfo.Gateway -ne "No Gateway" -and $AdapterInfo.Gateway -ne "Not Connected") {
$PingDestinationsCurrent += $AdapterInfo.Gateway
}
}
}
# Collect adapter information
$AdapterResults += $AdapterInfo
}
}
# Determine Primary Connection
$primaryConnection = "Unknown"
$defaultRoutes = Get-NetRoute -DestinationPrefix "0.0.0.0/0"
if ($defaultRoutes) {
# Exclude routes with invalid NextHop addresses
$defaultRoutes = $defaultRoutes | Where-Object {
$_.NextHop -ne '0.0.0.0' -and
$_.NextHop -ne '::'
}
if ($defaultRoutes) {
$primaryRoute = $defaultRoutes | Sort-Object -Property RouteMetric, ifMetric | Select-Object -First 1
$primaryInterfaceIndex = $primaryRoute.ifIndex
$primaryInterface = Get-NetAdapter | Where-Object { $_.ifIndex -eq $primaryInterfaceIndex }
if ($primaryInterface) {
$primaryConnection = $primaryInterface.Name
} else {
$primaryConnection = "Unknown"
}
} else {
$primaryConnection = "No Active Connection"
}
} else {
$primaryConnection = "No Active Connection"
}
# Add additional ping destinations
$PingDestinationsCurrent += $AdditionalPingDestinations
# Perform latency tests
if ($PingDestinationsCurrent.Count -gt 0) {
foreach ($dest in $PingDestinationsCurrent) {
try {
$pingResult = Test-Connection -ComputerName $dest -Count 1 -ErrorAction Stop
if ($pingResult) {
$latency = ($pingResult | Select-Object -First 1).ResponseTime
$LatencyResults[$dest] = "$latency ms"
} else {
$LatencyResults[$dest] = "No Response"
}
} catch {
$LatencyResults[$dest] = "Unreachable"
}
}
}
# TCP Connectivity Tests
if ($TcpTestHosts.Count -gt 0) {
foreach ($entry in $TcpTestHosts) {
if ($entry -match "^(.*?):(\d+)$") {
$host = $Matches[1]
$port = [int]$Matches[2]
$tcpTestResult = ""
$tcpLatency = ""
try {
$tcpTest = Measure-Command {
$tcpConnection = Test-NetConnection -ComputerName $host -Port $port -InformationLevel Quiet
}
if ($tcpConnection) {
$tcpTestResult = "Open"
$tcpLatency = "{0} ms" -f ($tcpTest.TotalMilliseconds)
} else {
$tcpTestResult = "Closed"
$tcpLatency = "N/A"
}
} catch {
$tcpTestResult = "Error"
$tcpLatency = "N/A"
}
$TcpTestResults += [PSCustomObject]@{
Host = $host
Port = $port
Result = $tcpTestResult
ConnectionTime = $tcpLatency
}
} else {
# Invalid entry format
$TcpTestResults += [PSCustomObject]@{
Host = $entry
Port = "Unknown"
Result = "Invalid Format"
ConnectionTime = "N/A"
}
}
}
}
# DNS resolution for specified hostnames
if ($DnsHostnames.Count -gt 0) {
function Resolve-Hostname {
param(
[string]$Hostname
)
try {
$resolvedIPs = Resolve-DnsName -Name $Hostname -ErrorAction Stop | Where-Object { $_.Type -eq 'A' } | Select-Object -ExpandProperty IPAddress
if ($resolvedIPs) {
return ($resolvedIPs -join ", ")
} else {
return "Not Resolved"
}
} catch {
return "Error"
}
}
foreach ($hostname in $DnsHostnames) {
$ipAddresses = Resolve-Hostname -Hostname $hostname
$DnsResults[$hostname] = $ipAddresses
}
}
# Construct the log entry
$logEntry = "$timestamp - Primary Connection: $primaryConnection"
# Add adapter information
foreach ($AdapterInfo in $AdapterResults) {
$logEntry += ", Adapter: $($AdapterInfo.Name), IP: $($AdapterInfo.IPAddress), Gateway: $($AdapterInfo.Gateway)"
}
# Add latency results
foreach ($dest in $PingDestinationsCurrent) {
$latency = $LatencyResults[$dest]
$logEntry += ", Latency to $dest`: $latency"
}
# Add TCP connectivity results
foreach ($tcpTest in $TcpTestResults) {
$logEntry += ", TCP Port $($tcpTest.Port) to $($tcpTest.Host): $($tcpTest.Result), Connection Time: $($tcpTest.ConnectionTime)"
}
# Add DNS resolution results
foreach ($hostname in $DnsHostnames) {
$ipAddresses = $DnsResults[$hostname]
$logEntry += ", $hostname IP: $ipAddresses"
}
# Write to log file
$logEntry | Out-File -FilePath $logFilePath -Append -Encoding UTF8
# Write to console
Write-Host $logEntry
Start-Sleep -Seconds 1
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment