我實現了我的第一個PowerShell腳本,做一些設置,設置註冊表項,並在隨後端需要重新啓動服務。問題是我只有可執行文件的名稱,但沒有服務名稱。重新啓動服務只能與服務的名稱一起使用。谷歌搜索(還有Binging)周圍並沒有給我太多的結果。
我想知道是否有方法通過可執行文件名重新啓動服務?
我知道我可以通過可執行文件名得到進程,但只是終止進程並重新啓動它並不是好的選擇,因爲服務啓動/停止功能未被調用,並且可能無法正常工作。
謝謝。
我實現了我的第一個PowerShell腳本,做一些設置,設置註冊表項,並在隨後端需要重新啓動服務。問題是我只有可執行文件的名稱,但沒有服務名稱。重新啓動服務只能與服務的名稱一起使用。谷歌搜索(還有Binging)周圍並沒有給我太多的結果。
我想知道是否有方法通過可執行文件名重新啓動服務?
我知道我可以通過可執行文件名得到進程,但只是終止進程並重新啓動它並不是好的選擇,因爲服務啓動/停止功能未被調用,並且可能無法正常工作。
謝謝。
您可以嘗試使用WMI和做這樣的事情:
(gwmi win32_service | ?{$_.pathname -match "\\executable.exe "}) | Restart-Service
你可以做到這一點使用WMI:
$process = Get-Process sqlservr| select -ExpandProperty Id
Get-WmiObject win32_Service|
where {$process -contains $_.ProcessId}|
foreach {Restart-Service $_.Name}
編輯:更改腳本重新啓動服務,而不只是阻止它。
Get-WmiObject -Class Win32_Service -Filter "PathName LIKE '%PartOfTheName%'" -ComputerName PC1 | Foreach-Object{
$_.StopService()
$_.StartService()
}
#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"))
不能通過管道WMI服務實例的重新啓動,服務小命令。對象的類型不同。 –
@Shay:嘗試一下管道......做得棒極了! –
@Shay - 失望。請嘗試一下。 – manojlds