首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Powershell循环测试-NetConnection

Powershell循环测试-NetConnection
EN

Stack Overflow用户
提问于 2022-03-28 13:38:04
回答 1查看 1.2K关注 0票数 0

我对Powershell脚本有点陌生,我试图用Test-NetConnection工具创建一个简单的循环,但我不知道如何做到这一点。

这就是我所拥有的:

代码语言:javascript
复制
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"}

  • 如果tcpport没有打开,我希望脚本每10秒循环并发出文本“端口关闭”,直到它打开为止。当tcppport打开时,它应该显示“端口$tcpport打开”文本并终止。
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-03-28 14:57:42

我们可以使用while循环来实现这一点,只需对现有代码做一些修改:

代码语言:javascript
复制
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.
  • The while循环操作,直到( Test-NetConnection @tcnArgs ).TcpTestSucceeded返回true为止。换句话说,当TCP测试在循环中是failing.
  • Sleep时,循环代码运行,不需要检查constantly.
  • Once while循环退出,输出一个字符串,说明TCP端口是打开的

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71648436

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档