Public/ps1/Configuration/Service/Restart-ApprxrService.ps1
|
function Restart-ApprxrService { <# .SYNOPSIS Restarts the Apprxr Windows service. .DESCRIPTION Stops and then starts the Apprxr service using standard Windows service management cmdlets. Includes error handling and status verification. #> [CmdletBinding()] param( [string]$NameExtension, [int]$StopTimeoutSeconds = 30, [int]$StartTimeoutSeconds = 30 ) $serviceName = if ($NameExtension) { "ApprxrService$NameExtension" } else { Get-ServiceNameApprxr } try { Write-Host "Stopping service '$serviceName'..." -ForegroundColor Yellow Stop-Service -Name $serviceName -Force -ErrorAction Stop Write-Host "Service '$serviceName' stopped." -ForegroundColor Green # Wait for service to fully stop $stopWatch = [System.Diagnostics.Stopwatch]::StartNew() do { Start-Sleep -Milliseconds 500 $service = Get-Service -Name $serviceName -ErrorAction SilentlyContinue } while ($service.Status -eq 'StopPending' -and $stopWatch.Elapsed.TotalSeconds -lt $StopTimeoutSeconds) if ($service.Status -ne 'Stopped') { Write-Host "Service did not stop completely within $StopTimeoutSeconds seconds. Current status: $($service.Status)" -ForegroundColor Yellow } Write-Host "Starting service '$serviceName'..." -ForegroundColor Yellow Start-Service -Name $serviceName -ErrorAction Stop Write-Host "Service '$serviceName' started." -ForegroundColor Green # Wait for service to fully start $stopWatch = [System.Diagnostics.Stopwatch]::StartNew() do { Start-Sleep -Milliseconds 500 $service = Get-Service -Name $serviceName -ErrorAction SilentlyContinue } while ($service.Status -eq 'StartPending' -and $stopWatch.Elapsed.TotalSeconds -lt $StartTimeoutSeconds) # Verify final state $service = Get-Service -Name $serviceName -ErrorAction SilentlyContinue if ($service.Status -eq 'Running') { Write-Host "Service '$serviceName' is now Running." -ForegroundColor Green } else { Write-Host "WARNING: Service '$serviceName' status is $($service.Status), expected Running." -ForegroundColor Red } } catch { Write-Host "ERROR: Failed to restart service '$serviceName': $($_.Exception.Message)" -ForegroundColor Red throw } } |