I'm trying to build a release pipeline in devops that re-deploys a windows service to a deployment pool. That is all working quite nicely, the only problem is that when copying the new .exe for the windows-service to its directory I need to stop the windows-service. Currently I just run
sc.exe stop "service name"
but if the service is stopped for any reason, this will cause an error ("The service has not been started."). I therefore need a way to determin if the job is currently running, and only stop it then. The same would go for starting the service, as it has to be in a stopped state to start it again.
Any help would be appreciated.
I therefore need a way to determine if the job is currently running, and only stop it then.
You can Add a PowerShell task before the deploy step to run a script to check the service status, if the service is running, then stop it.
$ServiceName = 'service1'
$arrService = Get-Service -Name $ServiceName
while ($arrService.Status -eq 'Running')
{
Stop-Service $ServiceName -ErrorAction SilentlyContinue
write-host $arrService.status
write-host 'Service stopping'
Start-Sleep -seconds 10
$arrService.Refresh()
if ($arrService.Status -eq 'Stopped')
{
Write-Host 'Service is now Stopped'
}
}
The same would go for starting the service, as it has to be in a stopped state to start it again.
Do the same thing to add a PowerShell task running the script to check the service status, if the service is not running, then start it.
$ServiceName = 'services1'
$arrService = Get-Service -Name $ServiceName
while ($arrService.Status -ne 'Running')
{
Start-Service $ServiceName -ErrorAction SilentlyContinue
write-host $arrService.status
write-host 'Service starting'
Start-Sleep -seconds 10
$arrService.Refresh()
if ($arrService.Status -eq 'Running')
{
Write-Host 'Service is now Running'
}
}
You can write script to do the same things using SC
commands. This thread for your reference.