function Start-ServicesByTier { <# .SYNOPSIS Starts all services that fall under the Tier parameter .PARAMETER Tier Number specifing the tier of services .PARAMETER IncludeLowerTiers Also include services from all tiers lower than the provided tier. (With this switch present, -Tier 0 starts only tier 0 service names, 1 starts both tier 0 and 1 services, 2 starts tier 2, 1, and 0, ad infinitum.) Values provided above the number of defined tiers simply start all available tiered services. #> [CmdletBinding()] param( [Parameter(Mandatory = $true)] [ValidateRange(0, [int]::MaxValue)] [int]$Tier, [Parameter(Mandatory = $false)] [switch]$IncludeLowerTiers ) $hostname = $env:COMPUTERNAME $results = @{ Hostname = $hostname HasError = $false ReturnValue = @() } $maxTier = $Tier if ($IncludeLowerTiers) { $minTier = 0 } else { $minTier = $Tier } # Assigning $minTier to 0 if the $IncludeLowerTiers param is enabled, otherwise matching up the $min/$maxTier params to only iterate through one tier for ($i = $minTier; $i -le $maxTier; $i++) { # Because I want to make my conditionals more readable $isStartingTier0 = $i -eq 0 $stoppedServicesInTier = @() try { $stoppedServicesInTier = @() $servicesByTier = (Get-ServicesByTier -Tier $i) foreach ($service in $servicesByTier) { $serviceStatus = (Get-Service $service -ErrorAction SilentlyContinue).Status -eq "Stopped" if ($serviceStatus) { $stoppedServicesInTier += $service } } $hasStoppedServicesInTier = -not (Test-IsCollectionNullOrEmpty -Collection $stoppedServicesInTier) } catch { Write-Warning $_ } finally { if ($hasStoppedServicesInTier) { $startServicesResults += Start-ServicesInParallel -ServiceNamestoStart $stoppedServicesInTier -ReturnResults $results.ReturnValue = $startServicesResults $results.HasError = -not (Test-IsCollectionNullOrEmpty -Collection $results.ReturnValue) } else { Write-Host "All services in Tier $i were already running" $results.ReturnValue = @() } } if ($results.HasError -and $isStartingTier0) { # when Tier 0 (Subscription,Broker) fails to start, return results immediately so we can fail the job Write-Warning "Exceptions were thrown trying to start serivces in Tier $i" Write-Warning "Returning a list of Exceptions or ErrorRecords" } return $results } }