0
do

{

Try{
if (New-Object System.Net.Sockets.TCPClient -ArgumentList $server,3389 )  
{ 

Write-Host $server 'Ready for RDP connection'-ForegroundColor Green }
}
catch { write-warning $error[0] }
}until ($? -eq $true)

Above script block exit after exception can someone help how to continue until it gets true.

JosefZ
  • 1,564
  • 1
  • 10
  • 18
vicky
  • 45
  • 4

1 Answers1

1

About Automatic Variables:

$?

Contains the execution status of the last operation. It contains True if the last operation succeeded and False if it failed.

In your code, the last operation is (successful) Write-Warning $error[0].

I'd use Do { … } While ($true) with break statement after Write-Host $server 'Ready for RDP connection -ForegroundColor Green'

If you insist upon Until keyword then rewrite the code snippet as follows:

do {
  $LastSuccess = $true
  Try {
    if (New-Object System.Net.Sockets.TCPClient -ArgumentList $server,3389 )  
    {
       Write-Host $server 'Ready for RDP connection'-ForegroundColor Green
       ### here's a possible place for (facultative) break
    }
  }
  catch { 
    write-warning $error[0]
    $LastSuccess = $false
  }
} until ( $LastSuccess )

In any case, I'd store the New-Object System.Net.Sockets.TCPClient to a variable. This constructor will automatically attempt a connection if supplied the host name and port number of the remote host, and it's the case (-ArgumentList $server,3389). Then I'd suppose that a connection is established and should be closed (and its resources should be released) later in the script using Close() and/or Dispose() and/or Finalize() method(s).

BTW, the if inside try block is definitely superfluous…

JosefZ
  • 1,564
  • 1
  • 10
  • 18