Functions/Network/Test-PortConnection.ps1

Function Test-PortConnection
{
    [CmdletBinding()]
    Param
    (
        # Target Server/IP
        [Parameter(Mandatory=$true,valuefrompipeline=$true,position=0)]
        [string]
        $ComputerName,

        # Port to connect on
        [Parameter(mandatory=$false,position=1)]
        [Int]
        $Port = 443,

         # Optional Source Server (Windows Only)
        [Parameter(Mandatory=$false,ParameterSetName="remote",position=2)]
        [string]
        $SourceComputerName,

        # Credential to use in Source Server Connection
        [Parameter(Mandatory=$false,ParameterSetName="remote",position=3)]
        [pscredential]
        $Credential
    )
    Process
    {
        # switch execution based on ParameterSet
        $Output = switch ($PSCmdlet.ParameterSetName)
        {
            "remote" {Invoke-Command -ComputerName $SourceComputerName -Credential $Credential -ScriptBlock ${Function:Test-PortConnection} -ArgumentList $ComputerName,$Port}
            DEFAULT {
                $client = [net.sockets.tcpclient]::new()
                $test = try {$client.Connect($ComputerName,$Port);$true} catch {$false} finally {$client.Dispose()}
                [pscustomobject]([ordered]@{
                    Source = $env:COMPUTERNAME
                    SourceIP = (([System.Net.Dns]::Resolve($env:COMPUTERNAME)).addresslist.ipaddresstostring)
                    Destination = $ComputerName
                    DestinationIP = ([System.Net.Dns]::Resolve($ComputerName)).addresslist.ipaddresstostring
                    Port = $Port
                    Test = $test
                })   
            }
        }
        
        # Filter Down the Default Property sSet
        Set-PSObjectDefaultMembers -Object $Output -Properties Source
    }
}