ps/Modules/Alkami.PowerShell.Services/Public/Stop-ServicesInParallel.ps1
2023-05-30 22:51:22 -07:00

69 lines
2.4 KiB
PowerShell

function Stop-ServicesInParallel {
<#
.SYNOPSIS
Attempts to stop a list of services in parallel. It will kill the services if they do not respond in time.
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true)]
[ValidateNotNull()]
[array]$serviceNamestoStop,
[Parameter(Mandatory=$false)]
[int]$maxParallel = 30
)
$logLead = (Get-LogLeadName);
if ($maxParallel -lt 1) {
Write-Warning "$logLead maxParallel was set to less than 1. Minimum number of threads is 1, setting maxParallel to 30";
$maxParallel = 30;
}
# Define the script to stop an individual service.
$serviceStopScript = {
param(
$serviceName
)
Write-Host "[Stop-ServicesInParallel] Stopping service $serviceName";
$serviceStopped = Stop-AlkamiService -sName $serviceName;
$result = @{
Result = $serviceStopped
ServiceName = $serviceName
}
return $result;
}
Write-Host "$loglead Stopping $($serviceNamesToStop.Count) services.";
# Stop all the services in parallel.
$results = Invoke-Parallel -objects $serviceNamestoStop -script $serviceStopScript -numThreads $maxParallel;
# Figure out which services did not stop.
$badResults = $results | Where-Object { $_.Result -eq $false };
if(!(Test-IsCollectionNullOrEmpty $badResults)) {
Write-Warning "$logLead $($badResults.Count) services were not successfully stopped:"
foreach($service in $badResults) {
Write-Warning "$logLead`t$($service.ServiceName) was not stopped.";
}
Write-Warning "$logLead Attempting to stop services again."
$serviceNamestoStop = $badResults | ForEach-Object { $_.ServiceName };
$results = Invoke-Parallel -objects $serviceNamestoStop -script $serviceStopScript -numThreads $maxParallel;
}
# Figure out which services did not stop (again)
$badResults = $results | Where-Object { $_.Result -eq $false };
if(!(Test-IsCollectionNullOrEmpty $badResults)) {
$errorString = "$logLead Could not stop $($badResults.Count) services:";
foreach($service in $badResults) {
$errorString += "`n$logLead`tCould not stop $($service.ServiceName)";
}
Write-Error $errorString;
return;
}
Write-Host "$logLead Services were successfully stopped.";
}