[CmdletBinding()] param( [ValidateSet("start", "stop", "restart")] [string]$Action, [string]$ServiceName = "ScreenJobBackend" ) Set-StrictMode -Version Latest $ErrorActionPreference = "Stop" function Wait-ForStatus { param( [Parameter(Mandatory = $true)]$Service, [Parameter(Mandatory = $true)][System.ServiceProcess.ServiceControllerStatus]$TargetStatus, [int]$TimeoutSeconds = 20 ) $deadline = (Get-Date).AddSeconds($TimeoutSeconds) while ((Get-Date) -lt $deadline) { $Service.Refresh() if ($Service.Status -eq $TargetStatus) { return } Start-Sleep -Milliseconds 350 } throw "Timed out waiting for service '$($Service.ServiceName)' to reach status '$TargetStatus'." } $service = Get-Service -Name $ServiceName -ErrorAction Stop switch ($Action) { "start" { if ($service.Status -ne [System.ServiceProcess.ServiceControllerStatus]::Running) { Start-Service -Name $ServiceName -ErrorAction Stop Wait-ForStatus -Service $service -TargetStatus ([System.ServiceProcess.ServiceControllerStatus]::Running) } } "stop" { if ($service.Status -ne [System.ServiceProcess.ServiceControllerStatus]::Stopped) { Stop-Service -Name $ServiceName -Force -ErrorAction Stop Wait-ForStatus -Service $service -TargetStatus ([System.ServiceProcess.ServiceControllerStatus]::Stopped) } } "restart" { if ($service.Status -eq [System.ServiceProcess.ServiceControllerStatus]::Running) { Restart-Service -Name $ServiceName -Force -ErrorAction Stop } else { Start-Service -Name $ServiceName -ErrorAction Stop } Wait-ForStatus -Service $service -TargetStatus ([System.ServiceProcess.ServiceControllerStatus]::Running) } }