我对Powershell脚本有点陌生,我试图用Test-NetConnection工具创建一个简单的循环,但我不知道如何做到这一点。
这就是我所拥有的:
param(
[string]$tcpserveraddress,
[string]$tcpport
)
if (Test-NetConnection -ComputerName $tcpserveraddress -Port $tcpport -InformationLevel Quiet -WarningAction SilentlyContinue) {"Port $tcpport is open" }
else {"Port $tcpport is closed"}发布于 2022-03-28 14:57:42
我们可以使用while循环来实现这一点,只需对现有代码做一些修改:
param(
[string]$tcpserveraddress,
[string]$tcpport
)
$tcnArgs = @{
ComputerName = $tcpserveraddress
Port = $tcpport
WarningAction = 'SilentlyContinue'
}
while( !( Test-NetConnection @tcnArgs ).TcpTestSucceeded ) {
"Port $tcpport is closed"
Start-Sleep -Seconds 60
}
"Port $tcpport is open"由于您表示您是PowerShell新手,下面详细介绍一下它的工作原理:
为了提高可读性,为了提高可读性,我使用参数splatting来定义并传递cmdlet参数作为hashmap。下面是一些additionalanswers,为感兴趣的人解释更详细的喷溅。
-InformationLevel Quiet。在脚本中,我们通常需要详细的对象,因为它有更多关于它的信息,我们可以对它的properties.while循环操作,直到( Test-NetConnection @tcnArgs ).TcpTestSucceeded返回true为止。换句话说,当TCP测试在循环中是failing.while循环退出,输出一个字符串,说明TCP端口是打开的。
https://stackoverflow.com/questions/71648436
复制相似问题