I currently have a script that listens on a specified port. I would like this script to stop running after 5 seconds, regardless of getting connected to or not. Is there a way that I am able to do that? Some sort of delay
function listen-port ($port) {
$endpoint = new-object System.Net.IPEndPoint ([ipaddress]::any,$port)
$listener = new-object System.Net.Sockets.TcpListener $endpoint
$listener.start()
$listener.AcceptTcpClient() # will block here until connection
$listener.stop()
}
listen-port 25
If you are not going to do anything with the client, then you don’t have to accept them and can just stop listening:
You can utilize the asynchronous AcceptTcpClient methods (BeginAcceptTcpClient,EndAcceptTcpClient) if you need to do something with the client:
Another option would be to use the Pending method on the listener: