param( [string]$hostname = "example.com", [int]$port = 443 ) function Test-Port { param ( [string]$HostName, [int]$Port, [int]$Timeout = 5000 ) try { $tcpConnection = New-Object System.Net.Sockets.TcpClient $asyncResult = $tcpConnection.BeginConnect($HostName, $Port, $null, $null) $success = $asyncResult.AsyncWaitHandle.WaitOne($Timeout, $false) if ($success -and $tcpConnection.Connected) { $tcpConnection.Close() Write-Host "Successfully connected to $HostName on port $Port." return $true } else { Write-Host "Port $Port on $HostName is closed or unreachable." return $false } } catch { $errorMessage = $_.Exception.Message Write-Host ("Error connecting to $HostName on port ${Port}: " + $errorMessage) return $false } } # Test the hostname and port Test-Port -HostName $hostname -Port $port