Last active
November 8, 2017 15:28
-
-
Save ctigeek/2a0e74be8167a194eb2d to your computer and use it in GitHub Desktop.
Delete a windows service.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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