mystack
mystack

Reputation: 5492

Eliminate Inner Loop

i have two loops in my program.First loop for setting up the retry peocess and inner loop for testing a connection status.

for($retry=0;$retry<=3;$retry++)
{
while (!(Test-Connection "mycomputer"))
   {
    if (time exceed)
    {
    $status=$false
    Write-Host "machine is offline"
    break
    }
}
if($status)
{
Write-Host "machine is online"
break
}

}

is there any way to eliminate the inner loop without changing the output

Upvotes: 0

Views: 78

Answers (3)

Lieven Keersmaekers
Lieven Keersmaekers

Reputation: 58441

The other answers already go in depth about why you don't really need a loop but I wanted to add a solution to your refactoring question.

You can eliminate the inner loop and if statement by pre-initializing a $Result variable and changing it in your original loop if necessary.

Personally, I find this more readable (subjective) at the expense of an extra assignment up front.

$Result = "machine is online";
for($retry=0;$retry<=3;$retry++) {
    while (!(Test-Connection "mycomputer"))
       {
        if (time exceed)
        {
        $Result = "machine is offline"
        break
        }
}
Write-Host $Result

Edit To test for multiple computers in parallel, I use following worflow

workflow Test-WFConnection {
  param(
    [string[]]$computers
  )
    foreach -parallel ($computer in $computers) {        
        Test-Connection -ComputerName $computer -Count 1 -ErrorAction SilentlyContinue
  }
}

called as Test-WFConnection @("pc1", "pc2", ... , "pcn")

Not much of a difference when every computer is online but a world of difference when multiple computers are offline.

Upvotes: 0

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174485

Not entirely sure what you mean by "time exceeded" - time to do what?

If you want to wait between Test-Connection attempts, you can introduce an artificial delay with Start-Sleep:

$Computer = "mycomputer"
$TimeoutSeconds = 5

for($retry=0; $retry -lt 3; $retry++)
{
    if(Test-Connection -ComputerName $Computer -Count 1 -Quiet){
        # Didn't work
        Write-Host "Machine is offline"
        # Let's wait a few seconds before retry
        Start-Sleep -Seconds $TimeoutSeconds
    } else {
        Write-Host "Machine is online!"
        break
    }
}

The easiest way however, would be to use the Count and Delay parameters of Test-Connection:

$Status = Test-Connection -ComputerName $Computer -Count 3 -Delay $TimeoutSeconds

Upvotes: 1

Lo&#239;c MICHEL
Lo&#239;c MICHEL

Reputation: 26150

You don't have to use a loop as test-connection already have a count parameter

Upvotes: 0

Related Questions