Service script that stops itself

Ask your PowerShell-related questions, including questions on cmdlet development!
Forum rules
Do not post any licensing information in this forum.

Any code longer than three lines should be added as code using the 'Select Code' dropdown menu or attached as a file.
This topic is 1 year and 3 months old and has exceeded the time allowed for comments. Please begin a new topic or use the search feature to find a similar but newer topic.
Locked
User avatar
daniel kusnir
Posts: 75
Last visit: Tue May 23, 2023 10:50 am
Answers: 1

Service script that stops itself

Post by daniel kusnir »

Hello.

is it possible to properly stop and uninstall powershell service by itself ? not sure what i did wrong, but my service always hangs on Stopping ( stop Pending ) . i also tried to add uninstaller for itself, but that does not work either. Other method i tried was to call external script that would stop service, but it will end with same result. if i dont add Get-Service 'TimeSync' | Stop-Service -Force, it will just run indefinitely.

This is my code :

Code: Select all

function Stop-MyService
{
	$global:bRunService = $false # Signal main loop to exit
	$CountDown = 3 # Maximum wait for loop to exit
	while ($global:bServiceRunning -and $Countdown -gt 0)
	{
		Start-Sleep -Seconds 1 # wait for your main loop to exit
		$Countdown = $Countdown - 1
	}
	try
	{
		Get-Service 'TimeSync' | Stop-Service -Force
		Invoke-Expression "$ScriptDir\TimeSync.exe /u"
	}
	catch
	{
		Add-Content $logFile -Value "$(Get-Date) Error. $($Error.Exception |GM |Out-String)"
	}
}
User avatar
daniel kusnir
Posts: 75
Last visit: Tue May 23, 2023 10:50 am
Answers: 1

Re: Service script that stops itself

Post by daniel kusnir »

okay i figured it out. i need to first change startup type to disabled, otherwise when it is on Auto, it will auto start and freez in loop. If somebody needs it. this is what worked for me

Code: Select all


		Get-Service 'TimeSync' | Set-Service -StartupType Disabled
		reg add HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce /v UninstallTimeSync /f /t REG_SZ /d "C:\Windows\System32\TimeSync.exe /u"
		Get-Service 'TimeSync' | Stop-Service -Force	
User avatar
Alexander Riedel
Posts: 8479
Last visit: Thu Mar 28, 2024 9:29 am
Answers: 19
Been upvoted: 37 times

Re: Service script that stops itself

Post by Alexander Riedel »

The Stop-Service function is called when your service receives a stop command.
By trying to stop 'yourself' so to speak you prevent it from stopping.
The function is meant to give a service a chance to stop operation, close handles, connections etc.
not to stop itself.
Alexander Riedel
SAPIEN Technologies, Inc.
User avatar
daniel kusnir
Posts: 75
Last visit: Tue May 23, 2023 10:50 am
Answers: 1

Re: Service script that stops itself

Post by daniel kusnir »

hi Alexander. Are you sure ?
that is exactly what i am calling but service will not stop. it will execute what is inside but does not stop. At least not for my version that is PSStudio 208
User avatar
Alexander Riedel
Posts: 8479
Last visit: Thu Mar 28, 2024 9:29 am
Answers: 19
Been upvoted: 37 times

Re: Service script that stops itself

Post by Alexander Riedel »

The problem then is likely in your main function. You are not exiting or not exiting fast enough there. At least that is most commonly the problem when
$global:bRunService is set to false.
Alexander Riedel
SAPIEN Technologies, Inc.
User avatar
daniel kusnir
Posts: 75
Last visit: Tue May 23, 2023 10:50 am
Answers: 1

Re: Service script that stops itself

Post by daniel kusnir »

hmm. The only thing i did was to call stop-myservice directly in the end of main function. this is how its done ( simplified version ). is that not a proper way ? i only found documentation to old service process

Code: Select all

function Invoke-MyService
{
	$global:bServiceRunning = $true
	
	while ($global:bRunService)
	{	
		try 
		{
			if($global:bServicePaused -eq $false) #Only act if service is not paused
			{
				
					$script:Done = $true
					Stop-MyService
			}


function Stop-MyService
{
	if ($Done -eq $true)
	{
		$global:bRunService = $false # Signal main loop to exit
		$CountDown = 3 # Maximum wait for loop to exit
		while ($global:bServiceRunning -and $Countdown -gt 0)
		{
			Start-Sleep -Seconds 1 # wait for your main loop to exit
			$Countdown = $Countdown - 1
		}
		Get-Service 'TimeSync' | Set-Service -StartupType Disabled

User avatar
Alexander Riedel
Posts: 8479
Last visit: Thu Mar 28, 2024 9:29 am
Answers: 19
Been upvoted: 37 times

Re: Service script that stops itself

Post by Alexander Riedel »

Stop-MyService should only be called from the host, handling a stop service event.
The host code is handling this event:
https://learn.microsoft.com/en-us/dotne ... at-ext-7.0
and calling the Stop-MyService function in your script so YOU can handle that event in your code.
If you want your service to stop itself, the easiest way is to launch
Net stop "servicename"
This way the signal to stop comes from the outside and asynchronous.
Alexander Riedel
SAPIEN Technologies, Inc.
User avatar
daniel kusnir
Posts: 75
Last visit: Tue May 23, 2023 10:50 am
Answers: 1

Re: Service script that stops itself

Post by daniel kusnir »

thank you. i understand - it wasnt built for sole purpose. SO basically it should be shutdown and closed from outside.
User avatar
Alexander Riedel
Posts: 8479
Last visit: Thu Mar 28, 2024 9:29 am
Answers: 19
Been upvoted: 37 times

Re: Service script that stops itself

Post by Alexander Riedel »

Yes, that more or less applies to all services whether done in PowerShell or not.
They usually do not self terminate, meaning there is no actual built in mechanism for that.
The underlying OS is generally in charge of terminating, starting or re-starting a service as needed.
Installers do this generally when updating a service or a dependent service. But in all cases this is kicked off from the outside.
Is there any particular reason you need to have a service shut itself down? Just curious.
Alexander Riedel
SAPIEN Technologies, Inc.
User avatar
daniel kusnir
Posts: 75
Last visit: Tue May 23, 2023 10:50 am
Answers: 1

Re: Service script that stops itself

Post by daniel kusnir »

i needed to create process to detect if PC is connected to the internet. this can run for a day or for a month. Then force PC to sync time and then terminate itself. It should not be visible as script running in the background either. These were requirements from customer. Service is convenient, as it runs as soon as PC starts and run until stopped. And even though it is not suppose to terminate itself, it still works so i am satisfied. For short therm, its ok. For long run, i will have to create proper process to handle stop and uninstall.
This topic is 1 year and 3 months old and has exceeded the time allowed for comments. Please begin a new topic or use the search feature to find a similar but newer topic.
Locked