5

I was wondering if anyone could help me out with this. I have this statement to stop a service but at times the service sometimes doesn't stop due to dependencies so i added a start-sleep -s 5.

while($module | Get-Service | ? {$_.Status -eq "Running" -or $_.Status -eq "Stopping"}) 
{
   set-service $module -ComputerName $targetserver -StartupType Disabled -Status Stopped -PassThru
        ;
  Start-Sleep -Seconds 5 #keep repeating stop services every 5 seconds until all services have stopped 
}

I want to add a counter to stop the loop after 60 seconds and if the service is still running then to write-hostrn "Service not stopped."

Any help is appreciated. Thanks all.

1

1 Answer 1

7

60/5 = 12 loops.

while (test -and ($counter++ -lt 12)) {
    #stop-service 
    #start-sleep
}

But with that long test, it might be more readable as:

do 
{ 
    set-service $module -ComputerName $targetserver -StartupType Disabled -Status Stopped -PassThru
    Start-Sleep -Seconds 5

    $status = ($module | Get-Service).Status
    $loopCounter++

} while ($status -in ('Running', 'Stopping') -and ($loopCounter -lt 12))
Sign up to request clarification or add additional context in comments.

1 Comment

This is exactly what I needed. Thank you so much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.