none
Do... Until... / Multiple Conditions? RRS feed

  • Question

  • I thought I had my do / until down until I tried the following.

    I aim to stop a service on a remote device, hopefully gracefully, and if it fails to do so gracefully within a period of time, force kill the process.

    I'll call the process "syzygy" for sake of example.  What happens is, on the test target machine, when I attempt to stop syzygy from running, the service is stopping gracefully prior to the iterations equaling 50, so I don't have to force kill it.

    It *should* proceed to the "else" clause

    Regardless, I get the initial status message re: the state of the service, and then I just see the text of the code's "if ($i = 50)" down to the end of it's "else" clause.

    Is this a result of nesting a do/until within a do/until?

    $computer = Read-Host "Enter remote hostname or IP"
    
    ########################
    # Stop Syzygy
    
    $i = $null
    
    do 
        {
        $i++
        (Get-Service -ComputerName $computer -Name "Syzygy")
        sleep -Seconds 6
        }
    # Until the service has stopped *OR* attempts have gone to 5 minutes without success
    until ((Get-Service -ComputerName $computer -Name "Syzygy" | Where-Object {$_.Status -eq "Stopped"}) -or ($i = 50))
        {
        if ($i = 50)
            {
            Write-Host "$computer / Syzygy has *not* stopped gracefully." -ForegroundColor Yellow -BackgroundColor DarkRed
            do 
                {
                $syzygyproc = (Get-Process -ComputerName $computer -Name "Syzygy").Id
                Stop-Process -Id $syzygyproc -Force
                sleep -Seconds 6
                (Get-Service -ComputerName $computer -Name "Syzygy")
                }
            until (!$syzygyproc)
                {
                Write-Host "$computer / Syzygy Stopped Manually / Killed" -ForegroundColor Yellow -BackgroundColor DarkRed
                }
            }
        else
            {
            Write-Host "$computer / Syzygy Stopped Gracefully" -ForegroundColor Green
            }
        }
    
    
    

    Monday, December 11, 2017 6:32 PM

Answers

  • Get-Service Syzygy -ComputerName $computer | Stop-Service

    If this time out then get the service process and kill it.


    \_(ツ)_/

    • Marked as answer by BAWrites Monday, December 11, 2017 7:29 PM
    Monday, December 11, 2017 6:44 PM

All replies

  • Get-Service Syzygy -ComputerName $computer | Stop-Service

    If this time out then get the service process and kill it.


    \_(ツ)_/

    • Marked as answer by BAWrites Monday, December 11, 2017 7:29 PM
    Monday, December 11, 2017 6:44 PM
  • I'll give it a shot.  I like simpler!

    Monday, December 11, 2017 7:00 PM