Powershell help, if process exists, stop it, else start a service?

跟風遠走 提交于 2019-12-11 03:24:57

问题


I'm pretty new to Powershell. I have 2 different scripts I'm running that I would like to combine into one script.

Script 1 has 1 line

Stop-Process -ProcessName alcore.*  -force

It's purpose is to end any process that begines with "alcore."

Script 2 has 1 line as well

Start-Service -displayname crk*

It starts any service that begins with crk.

How can I combine these into one script? If the processes are running I wish to stop them, if not, I wish to start the services. How can I accomplish this?

I'm trying this but it's not working

$services = Get-Process alcore.*

if($services.Count -qe 1){
    Stop-Process -ProcessName alcore.*  -force
} else {

    Start-Service -displayname crk*
}

How can I do this correctly? Also should I wrap these up in a function and call the function? That seems a bit cleaner. Thanks for any help.

Cheers,
~ck


回答1:


Use Get-Service to get the service status. The process could be running but the service might be paused:

$services = @(Get-Service alcore.*)
foreach ($service in $services)
{
    if ($service.Status -eq 'Running')
    {
        $service | Stop-Service
    }
    else
    {
        Start-Service -DisplayName crk*
    }
}


来源:https://stackoverflow.com/questions/3143938/powershell-help-if-process-exists-stop-it-else-start-a-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!