function - powershell 中 "x"秒后停止函数

标签 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

最佳答案

如果您不打算对客户做任何事情,那么您不必接受他们并且可以停止倾听:

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()
}

关于function - powershell 中 "x"秒后停止函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13129952/

相关文章:

sharepoint - 获取网络分析

当 CSV 字段不存在时,Powershell 函数参数获取意外值

javascript - Node.js - 如何在函数之间传递参数

function - 如何从 Rust 中的子文件夹导入函数

javascript - 函数真的是一个对象吗

c - 如何返回结构类型的函数的返回值?

c - 我想知道为什么一个函数在从 x 调用时执行得很好,但在从 y 调用时却执行得不好

powershell - 了解Powershell中的循环结构

powershell - 路径中有括号的奇怪行为

powershell - 控制cmdlet定义的属性