Open a port on a Windows server using PS

I am using the following code to open a port on a Windows server so I can perform port checks to and from this server:

function Listen-Port ($port=80){
<#
.DESCRIPTION
Temporarily listen on a given port for connections dumps connections to the screen - useful for troubleshooting
firewall rules.

.PARAMETER Port
The TCP port that the listener should attach to

.EXAMPLE
PS C:\> listen-port 443
Listening on port 443, press CTRL+C to cancel

DateTime                                      AddressFamily Address                                                Port
--------                                      ------------- -------                                                ----
3/1/2016 4:36:43 AM                            InterNetwork 192.168.20.179                                        62286
Listener Closed Safely

.INFO
Created by Shane Wright. Neossian@gmail.com

#>
    $endpoint = new-object System.Net.IPEndPoint ([system.net.ipaddress]::any, $port)    
    $listener = new-object System.Net.Sockets.TcpListener $endpoint
    $listener.server.ReceiveTimeout = 3000
    $listener.start()    
    try {
    Write-Host "Listening on port $port, press CTRL+C to cancel"
    While ($true){
        if (!$listener.Pending())
        {
            Start-Sleep -Seconds 1; 
            continue; 
        }
        $client = $listener.AcceptTcpClient()
        $client.client.RemoteEndPoint | Add-Member -NotePropertyName DateTime -NotePropertyValue (get-date) -PassThru
        $client.close()
        }
    }
    catch {
        Write-Error $_          
    }
    finally{
            $listener.stop()
            Write-host "Listener Closed Safely"
    }

}

After consecutive connections the output looks like this:

DateTime AddressFamily Address Port


16/09/2022 12:48:28 PM InterNetwork 127.0.0.1 55473
16/09/2022 12:49:06 PM InterNetwork 127.0.0.1 55618
16/09/2022 12:49:30 PM InterNetwork 127.0.0.1 55696

And this is what I expected. So far so good.

The only problem is that the first time the code is run, with the first connection to the port, I can see the cursor drop one line, however nothing is displayed. I close that connection and connect again, and then both the previous and new connection details are displayed.

The output comes from the “$client.client.RemoteEndPoint | Add-Member…” line. It seems the connection is “saved” to this variable but not displayed until a second connection occurs.

Any suggestions on how to fix this?