2011-08-18 44 views
1

所有的PowerShell:重新启动服务通过可执行文件名称

我实现了我的第一个PowerShell脚本,做一些设置,设置注册表项,并在随后端需要重新启动服务。问题是我只有可执行文件的名称,但没有服务名称。重新启动服务只能与服务的名称一起使用。谷歌搜索(还有Binging)周围并没有给我太多的结果。

我想知道是否有方法通过可执行文件名重新启动服务?

我知道我可以通过可执行文件名得到进程,但只是终止进程并重新启动它并不是好的选择,因为服务启动/停止功能未被调用,并且可能无法正常工作。

谢谢。

回答

4

您可以尝试使用WMI和做这样的事情:

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

不能通过管道WMI服务实例的重新启动,服务小命令。对象的类型不同。 –

+1

@Shay:尝试一下管道......做得棒极了! –

+0

@Shay - 失望。请尝试一下。 – manojlds

0

你可以做到这一点使用WMI:

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

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

编辑:更改脚本重新启动服务,而不只是阻止它。

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

这应该如何工作? – manojlds

+0

噢,我用名称代替PathName,谢谢你的收获! –

+0

如果多个服务具有相同的.exe,该怎么办?我有多个使用sqlservr.exe的服务。另外,如果有一个服务使用“AnotherExename.exe”(“%”通配符会导致它匹配);不太可能,但可能。 – Rynant

0
#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")) 
相关问题