1

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"}
  • If the tcpport is not open, I would like the script to loop and issue the text "Port $tcpport is closed" every 10 seconds, until it is open.
  • When tcppport is open, it should display the "Port $tcpport is open" text and terminate.
J. Scott Elblein
  • 4,013
  • 15
  • 58
  • 94
Eric van Loon
  • 103
  • 1
  • 9

1 Answers1

2

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
codewario
  • 19,553
  • 20
  • 90
  • 159