在powershell中“x”秒后停止功能

时间:2012-10-29 21:28:20

标签: function powershell

我目前有一个侦听指定端口的脚本。我希望这个脚本在5秒后停止运行,无论是否连接。有没有办法让我能够做到这一点?某种延迟

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

1 个答案:

答案 0 :(得分:2)

如果您不打算与客户做任何事情,那么您不必接受它们,只能停止倾听:

function listen-port ($port) {
$endpoint = new-object System.Net.IPEndPoint ([ipaddress]::any,$port)
$listener = new-object System.Net.Sockets.TcpListener $endpoint
$listener.start()
Start-Sleep -s 5
$listener.stop()
}

如果您需要对客户端执行某些操作,可以使用异步AcceptTcpClient方法(BeginAcceptTcpClientEndAcceptTcpClient):

function listen-port ($port) {
$endpoint = new-object System.Net.IPEndPoint ([ipaddress]::any,$port)
$listener = new-object System.Net.Sockets.TcpListener $endpoint
$listener.start()
$ar = $listener.BeginAcceptTcpClient($null,$null) # will not block here until connection

if ($ar.AsyncWaitHandle.WaitOne([timespan]'0:0:5') -eq $false) 
{ 
 Write-Host "no connection within 5 seconds" 
}
else
{ 
 Write-Host "connection within 5 seconds"
 $client = $listener.EndAcceptTcpClient($ar)
}

$listener.stop()
}

另一种选择是在侦听器上使用Pending方法:

function listen-port ($port) {
$endpoint = new-object System.Net.IPEndPoint ([ipaddress]::any,$port)
$listener = new-object System.Net.Sockets.TcpListener $endpoint
$listener.start()
Start-Sleep -s 5

if ($listener.Pending() -eq $false)
{
 Write-Host "nobody connected"
} 
else
{ 
 Write-Host "somebody connected"
 $client = $listener.AcceptTcpClient()
}

$listener.stop()
}