Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

loop until IP:port is responding

I have a simple inquire but test-netConnection or test-connection are giving me a hard time while used in a loop. So basically I want to run in a loop until a server is responding to my connection attempt on a certain port. With test-connection I see that you cannot specify a port, so the solution I guess is to use tnc - test-netconnection.

In a do while loop it doesn't work as tnc doesn't use a continuous ping/connect attempts.

do {
  Write-Host "waiting..."
  sleep 3      
} until(Test-NetConnection $HOST -Port PORT)
like image 592
user3144292 Avatar asked Mar 15 '14 22:03

user3144292


1 Answers

The code above doesn't work because the until test only verifies if the result is not null. Test-NetConnection always returns an object(even with false as a status), so the test would always be "true", which means that your do { } scriptblock would only run once no matter what the result is. One solution would be to make the until test check one of the properties returned, like this:

do {
  Write-Host "waiting..."
  sleep 3      
} until(Test-NetConnection $HOST -Port PORT | ? { $_.TcpTestSucceeded } )
like image 106
Frode F. Avatar answered Nov 15 '22 20:11

Frode F.