Search code examples
powershellpowershell-cmdlet

Does the powershell cmdlet 'Stop-Service' prevent the rest of the script from executing until the service has stopped?


I am writing a script to shut down a list of services using the Stop-Service cmdlet.

My question is: does the Stop-Service cmdlet wait until the service has stopped before continuing with the rest of the script? Or does the script immediately continue after executing the Stop-Service command regardless of outcome?

Script below

[System.Collections.ArrayList]$Services = 'service1','service2','service3';

#Stop Services
foreach ($svcName in $Services) {
    $serviceObj = Get-Service -name $svcName
    if($serviceObj.Status -eq 'Running') {
        Stop-Service $serviceObj
    }
}

For example: if all services take 10 seconds to stop each, will this script take 10 seconds to run or 30? (Assuming successful shut down)

I am trying to determine how long this script will take on average.


Solution

  • As per my comment.

    ($Stopwatch = [Diagnostics.Stopwatch]::StartNew())
    
    (
        Get-Service | 
        Select-Object -Property Name, Status
    ) -match 'Running' | 
    Select-Object -First 3 | 
    Stop-Service
    
    $Stopwatch.Elapsed
    # Resuults
    <#
    Days              : 0
    Hours             : 0
    Minutes           : 0
    Seconds           : 6
    Milliseconds      : 182
    Ticks             : 61827905
    TotalDays         : 7.15600752314815E-05
    TotalHours        : 0.00171744180555556
    TotalMinutes      : 0.103046508333333
    TotalSeconds      : 6.1827905
    TotalMilliseconds : 6182.7905
    #>