Powershell帮助,如果存在进程,则停止它,否则启动服务? [英] Powershell help, if process exists, stop it, else start a service?
问题描述
我对Powershell很陌生。我有2种正在运行的脚本,我想将它们组合成一个脚本。
I'm pretty new to Powershell. I have 2 different scripts I'm running that I would like to combine into one script.
脚本1有1行
Stop-Process -ProcessName alcore.* -force
其目的是结束任何以 alcore开头的过程。
It's purpose is to end any process that begines with "alcore."
脚本2也有1行
Start-Service -displayname crk*
启动任何以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?
我正在尝试但不起作用
$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.
干杯,
〜ck
Cheers,
~ck
推荐答案
使用Get-Service获取服务状态。该进程可能正在运行,但服务可能已暂停:
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*
}
}
这篇关于Powershell帮助,如果存在进程,则停止它,否则启动服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!