Eric van Loon
Eric van Loon

Reputation: 133

Powershell looping Test-NetConnection

I'm a bit new to Powershell scripting and I'm trying to create a simple loop with the Test-NetConnection tool, but I don't know how to do this.

This is what I have:

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"}

Upvotes: 1

Views: 9006

Answers (1)

codewario
codewario

Reputation: 21488

We can use a while loop to achieve this with a few modifications to your existing code:

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"

Since you indicated you are new to PowerShell, here's a breakdown of how this works:

  • For the sake of readability, I have use argument splatting to define and pass the cmdlet parameters as a hashmap. Here are some additional answers that explain splatting in more detail, for those interested.
  • No longer use -InformationLevel Quiet. In a script we generally want the detailed object as it has more information on it, and we can operate off of its properties.
  • The while loops, until ( Test-NetConnection @tcnArgs ).TcpTestSucceeded returns true. In other words, the loop code runs while the TCP test is failing.
  • Sleep in the loop, no need to check constantly.
  • Once the while loop exits, output a string stating the TCP port is open

Upvotes: 2

Related Questions