PowerShell:按可执行文件名重新启动服务

时间:2011-08-18 01:33:29

标签: windows scripting powershell windows-services

所有

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

我想知道是否有办法按可执行文件名重启服务?

我知道我可以通过可执行文件名来获取进程,但是只是杀死进程并重新启动它不是一个好选择,因为服务启动/停止功能没有被调用,它可能无法正常工作。

感谢。

4 个答案:

答案 0 :(得分:4)

您可以尝试使用wmi并执行以下操作:

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

答案 1 :(得分:1)

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

答案 2 :(得分:0)

您可以使用WMI执行此操作:

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

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

编辑:更改了脚本以重新启动服务,而不仅仅是停止它。

答案 3 :(得分: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"))
相关问题