Function to stop and start service

Hi guys,

I am trying to create a function which will start and stop a service depending on if a process is running.

The code i have written seems to work but fails after a certain amount of time with the following error:

“The script failed due to call depth overflow”.

in order for my script to work i need to have the function constantly running so that it can find the process and carry out a relevant task. This is why i have done a while loop at the end of the script to keep it running. From doing some research this seems to be my issue, but cant find a way around it.

Any help will be much appreciated :slight_smile:

My is below:

function Find-process {

do {

#find BAM process

$processfound = Get-Process -Name BusinessAlertManager -ErrorAction Ignore

#When process is found stop the service (Allows the application to open).

if ($processfound) {

Stop-Service -Name BAMService

}

else {

Start-Service -Name BAMService

}

}

until ($processfound)

#Run continuously on ext and opening of the application

while($true) {

 Find-process;

}

}

Duane (are you “The Rock”? :wink: ),
Welcome to the forum. :wave:t4:

When you post code, error messages, console output or sample data please format it as code using the “preformatted text” button ( </> ).

Thanks in advance.

If it’s really just this that’s all you need:

while ($true) {
    if (Get-Process -Name BusinessAlertManager -ErrorAction SilentlyContinue) {
        Stop-Service -Name BAMService
    }
    else {
        Start-Service -Name BAMService
    }
    Start-Sleep -Seconds 5
}

No function needed. :wink: … I added a Start-Sleep inside the loop to reduce the stress you put on your machine with this simple snippet.

ahh that seems to work perfectly for what i need.

Not to sure why i thought using a function was the only way to go rather than using a while loop.

Still learning…:slight_smile:

Thanks for the help !

Great. I’m glad it was helpful.

I used to consider a function when I notice that I write the same line of code twice or more in one script.

We all are … :wink: