11 December 2007

Remove that pesky Windows Service

I have been writing a Windows Service (no easy feat, let me tell you) in Visual Studio and have found that getting it off the machine is just as difficult.

Following is a batch file to remove the service in question. The process is as follows: Use Add/Remove programs to get rid of the service, then run this batch file. One word of warning, the machine needs to be rebooted in order to remove the service.

VB Script File


On Error Resume Next

Const HKEY_LOCAL_MACHINE = &H80000002

strComputer = "."
strKeyPath1 = "SYSTEM\ControlSet001\Services\[ServiceName]"
strKeyPath2 = "SYSTEM\ControlSet001\Services\Eventlog\Application\[ServiceName]"
strKeyPath3 = "SYSTEM\ControlSet002\Services\[ServiceName]"
strKeyPath4 = "SYSTEM\ControlSet002\Services\EventLog\Application\[ServiceName]"
strKeyPath5 = "SYSTEM\CurrentControlSet\Services\EventLog\Application\[ServiceName]"
strKeyPath6 = "SYSTEM\ControlSet001\Services\Eventlog\Application\[ServiceName].[ServiceName]"
strKeyPath7 = "SYSTEM\ControlSet002\Services\Eventlog\Application\[ServiceName].[ServiceName]"
strKeyPath8 = "SYSTEM\CurrentControlSet\Services\Eventlog\Application\[ServiceName].[ServiceName]"


Set objRegistry = GetObject("winmgmts:\\" & _
strComputer & "\root\default:StdRegProv")

DeleteSubkeys HKEY_LOCAL_MACHINE, strKeypath1
DeleteSubkeys HKEY_LOCAL_MACHINE, strKeypath2
DeleteSubkeys HKEY_LOCAL_MACHINE, strKeypath3
DeleteSubkeys HKEY_LOCAL_MACHINE, strKeypath4
DeleteSubkeys HKEY_LOCAL_MACHINE, strKeypath5
DeleteSubkeys HKEY_LOCAL_MACHINE, strKeypath6
DeleteSubkeys HKEY_LOCAL_MACHINE, strKeypath7
DeleteSubkeys HKEY_LOCAL_MACHINE, strKeypath8

Set WSHShell = WScript.CreateObject("WScript.Shell")
WshShell.Run "C:\WINDOWS\system32\shutdown.exe -r -t 0"

Sub DeleteSubkeys(HKEY_LOCAL_MACHINE, strKeyPath)
objRegistry.EnumKey HKEY_LOCAL_MACHINE, strKeyPath, arrSubkeys

If IsArray(arrSubkeys) Then
For Each strSubkey In arrSubkeys
DeleteSubkeys HKEY_LOCAL_MACHINE, strKeyPath & "\" & strSubkey
Next
End If

objRegistry.DeleteKey HKEY_LOCAL_MACHINE, strKeyPath
End Sub