Powershell Wait for service to be stopped or started

后端 未结 4 843
暗喜
暗喜 2021-01-31 19:36

I have searched both this forum and through google and can\'t find what I need. I have a quite large script and I\'m looking for some code that will check if the service is star

4条回答
  •  盖世英雄少女心
    2021-01-31 20:15

    I couldn't get the 'count' strategy, that Micky posted, to work, so here is how i solved it:

    I created a function, that takes a searchString (this could be "Service Bus *") and the status that i expect the services should reach.

    function WaitUntilServices($searchString, $status)
    {
        # Get all services where DisplayName matches $searchString and loop through each of them.
        foreach($service in (Get-Service -DisplayName $searchString))
        {
            # Wait for the service to reach the $status or a maximum of 30 seconds
            $service.WaitForStatus($status, '00:00:30')
        }
    }
    

    The function can now be called with

    WaitUntilServices "Service Bus *" "Stopped"
    

    or

    WaitUntilServices "Service Bus *" "Running"
    

    If the timeout period is reached, a not so graceful exception is thrown:

    Exception calling "WaitForStatus" with "2" argument(s): "Time out has expired and the operation has not been completed."
    

提交回复
热议问题