Skip to content

Instantly share code, notes, and snippets.

@carkrueger
Created January 4, 2015 12:14
Show Gist options
  • Save carkrueger/203a86efe35bdd349b34 to your computer and use it in GitHub Desktop.
Save carkrueger/203a86efe35bdd349b34 to your computer and use it in GitHub Desktop.
Stop service, if not possible kill
1: function Kill-Service() {
2: param(
3: [Parameter(Mandatory=$true)]
4: [string]$srvcName,
5: [Parameter(Mandatory=$false)]
6: [string]$ComputerName='.',
7: [Parameter(Mandatory=$false)]
8: [string]$TimeOut='00:00:05'
9: )
10: $srvName
11: $ComputerName
12: $TimeOut
13: #Invoke-Command -cn $ComputerName -ArgumentList $srvcName -ScriptBlock {
14: Invoke-Command -ArgumentList $srvcName -ScriptBlock {
15: $svc = Get-Service $srvcName
16: if ($svc -ne $null) {
17: try {
18: Write-Host($svc.Name)
19: $svc.stop() # stoppe Service
20: $svc.WaitForStatus('Stopped',$TimeOut) # Warte $Timeout auf Stop von Service
21: Write-Host ('Service exited gracefully')
22: }
23: catch [System.ServiceProcess.TimeoutException] {
24: #sichere Service FailureActions
25: $regpath="HKLM:\SYSTEM\CurrentControlSet\Services\"+$srvcName
26: $before=(Get-ItemProperty -Path $regpath -Name FailureActions).FailureActions
27: Write-Host('Recovery Settings saved')
28: # ermittele PID des Service-Prozesses
29: $ServiceNamePID = Get-Service $srvcName
30: $ServicePID = (Get-WmiObject Win32_Service | Where {$_.Name -eq $ServiceNamePID.Name}).ProcessID
31: set-itemproperty -Path $regpath -Name FailureActions -Value ([byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x03,0x00,0x00,0x00,0x14,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x60,0xea,0x00,0x00,0x00,0x00,0x00,0x00,0x60,0xea,0x00,0x00,0x00,0x00,0x00,0x00,0x60,0xea,0x00,0x00))
32: Write-Host('Recovery Settings overwritten')
33: Stop-Process $ServicePID -Force
34: Write-Host('Process ' + $ServicePID + ' Killed')
35: #(Get-WmiObject -class win32_process -filter ('ProcessId = '+$ServicePID)).terminate()
36: set-itemproperty -Path $regpath -Name FailureActions -Value $before
37: Write-Host('Recovery Settings restored')
38: }
39: catch [Exception] {
40: write-host $_.Exception.GetType().FullName;
41: write-host $_.Exception.Message;
42: }
43: }
44: else
45: {
46: Write-Host('No Service returned')
47: }
48: }
49: }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment