Skip to content

Instantly share code, notes, and snippets.

@ctigeek
Last active November 8, 2017 15:28
Show Gist options
  • Select an option

  • Save ctigeek/2a0e74be8167a194eb2d to your computer and use it in GitHub Desktop.

Select an option

Save ctigeek/2a0e74be8167a194eb2d to your computer and use it in GitHub Desktop.
Delete a windows service.
function Remove-Service {
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True,ValueFromPipeline=$True)] [object] $service
)
BEGIN { }
PROCESS {
$serviceName = $service.Name
if (-not $serviceName) {
throw "Not a valid service!"
}
Stop-Service $service
Start-Sleep -Seconds 5
$nameFilter = "Name='$($serviceName)'"
$wmiservice = Get-WmiObject -Class Win32_Service -Filter "$nameFilter" -ComputerName $service.MachineName
if ($wmiservice) {
$wmiservice.delete()
Start-Sleep -Seconds 2
##This next part (usually) solves the "this service has been marked for deletion" issue in windows.
$service = Get-Service $serviceName -ErrorAction SilentlyContinue
if ($service) {
Stop-Service $service
Start-Sleep -Seconds 2
$service = Get-Service $serviceName
if ($service) {
throw "Unable to remove the service."
}
}
}
else {
Write-Warning "Wmi Service not found. Verify the service currently exists."
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment