Wednesday, January 25, 2017

Uninstall Windows Service using PowerShell

You can get a list of services using the Get-Service cmdlet, for example, to retrieve a list of all running services you could run:

Get-Service | Where-Object { $_.Status -eq "Running" }

You could even retrieve a specific service and start/stop it:

$service = Get-Service DemoService
$service.Start()
$service.Stop()

However, there is nothing to remove the service on this object.

We can also use GetWmiObject to do the same things:

$service = Get-WmiObject Win32_Service -Filter "name='DemoService'"
$service.StartService()
$service.StopService()

But this WMI object actually also exposes a delete functionality, which will mark the service to be deleted.

$service = Get-WmiObject Win32_Service -Filter "name='DemoService'"
$service.Delete()

If there are resources that are being held onto, it will only be deleted once they're freed up - whether it's the service that needs to gracefully shutdown still, or maybe the services manager snap-in (services.msc) has an open properties window open (I think that's happened to me before), and closing it then puts the delete through.