2011-08-18 46 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")) 
相關問題