开发者

PowerShell: Restart Service By Executable Name

all

I impl开发者_StackOverflow中文版emented my first PowerShell script, that does some setup, sets registry keys and at then end needs to restart services. The problem is that I have only have name of the executable, but not service name. Restart-Service can work only with name of the service. Googling (well Binging also) around didn't give me much result.

I was wondering whether there is a way to restart service by executable name?

I know that I can get process by executable name, but just killing the process and starting it again is NOT good choice, since service Start/Stop functions are not called and it may not work properly.

Thanks.


You can try using wmi and do something like this:

(gwmi win32_service | ?{$_.pathname -match "\\executable.exe "}) | Restart-Service


Get-WmiObject -Class Win32_Service -Filter "PathName LIKE '%PartOfTheName%'" -ComputerName PC1 | Foreach-Object{
    $_.StopService()
    $_.StartService()   
}


You can do this using WMI:

$process = Get-Process sqlservr| select -ExpandProperty Id

Get-WmiObject win32_Service| 
    where {$process -contains $_.ProcessId}|
    foreach {Restart-Service $_.Name}

Edit: Changed script to restart service, not just stop it.


#set by logic to determine if the service will restart or not
 $global:ServerWillRestart=$true 

#can be found using the name column of Get-services cmdlet
 $serviceName="Set name of the service" 
if($global:ServerWillRestart){
     $service =Get-Service | where{ $_.Name -eq $serviceName}
do{
    Write-output "The service $ServiceName will is being stopped"
    Stop-Service $service
    Start-Sleep -s 2
}
while($service.WaitForStatus("Stopped"))

do{
    Write-Output "The service $ServiceName will is being started"
    Start-Service $service
    Start-Sleep -s 2
}
while($service.WaitForStatus("Running"))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜