How to Stop a Windows Service after 15 attempts in Octopus Deploy By Using Power Shell Scripting

Hi,
This is Ram,I’m starting a windows service using Power shell Start-Service in a deploy step, but that command waits maximum 240 more than attempts and returns an error or its success. I want to stop a Windows Service(Ex: Sales Service) after 15 attempts to app server in Octopus Deploy By using Power shell Scripting, Its Stopped service automatically. How to Write this Power shell Script, Please Help me for this ASAP.

Hi Ram,

Thanks for getting in touch! Unfortunately we cannot write PowerShell scripts for you to use with Octopus, it is not part of a service that we offer.
Have you reached out to PowerShell user forums for assistance? They would be a great place to start.

Vanessa

Set-StrictMode -Version Latest;

$ServiceName      = 'YourServiceName';
$TimeOutInSeconds = 20;

Write-Output "Attempting to stop windows service $ServiceName";

Try {

	Write-Output "Searching for windows service $ServiceName";
	$ServiceController = Get-Service $ServiceName -ErrorAction SilentlyContinue;
	
	If ($ServiceController -ne $null)
	{
    	If ($ServiceController.Status -ne [ServiceProcess.ServiceControllerStatus]::Stopped)
    	{
    		Write-Error ("Windows service $ServiceName is in a {0} state" -f $serviceController.Status) -ErrorAction Continue;
    	}
    	
    	Write-Output "Issuing stop command for $ServiceName";
    	Stop-Service $ServiceName;
    	Write-Output "Waiting for $TimeOutInSeconds (seconds) for windows service $ServiceName to stop";
    	$ServiceController.WaitForStatus([ServiceProcess.ServiceControllerStatus]::Stopped, [TimeSpan]::FromSeconds($TimeOutInSeconds));
    	Write-Output "Successfully stopped windows service $ServiceName";
	}
	Else
	{
	    Write-Output "Service $ServiceName is not installed"
	}
}
Catch [TimeoutException]
{
	Write-Error "Failed to stop windows service $ServiceName, as it did not stop within the specified period of $TimeOutInSeconds (seconds)" -ErrorAction Stop
}
Catch {
	Write-Error "Failed to stop windows service $ServiceName`n$(Resolve-Error)" -ErrorAction Stop
}

Just to add to the working code posted above. This can easily be added as a step template and pass the service name and timeout as parameters, which is how we did this.

You can add parameters to the Step Template and set them like this
$ServiceName = $OctopusParameters[‘ServiceName’];
$TimeOutInSeconds = $OctopusParameters[‘TimeOutInSeconds’];

I’ve shown an example for Stopping a service as it handles all the common scenarios - service not installed but you want to be sure that if it is, that it is stopped.

To make it a start service just amend the comments and the method call:
Stop-Service $ServiceName;
to
Start-Service $ServiceName;