Skip to content

Commit fb0dbe8

Browse files
committed
Update Remove-WindowsServiceCIM
rename, improve and bump
1 parent 547535c commit fb0dbe8

File tree

2 files changed

+58
-42
lines changed

2 files changed

+58
-42
lines changed

ps-services/DeleteServicesCIM.ps1

Lines changed: 0 additions & 42 deletions
This file was deleted.
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
Function Remove-WindowsServiceCIM {
2+
<#
3+
.SYNOPSIS
4+
Windows services removal script.
5+
6+
.DESCRIPTION
7+
This function deletes Windows services using the CIM method.
8+
9+
.PARAMETER ServiceNames
10+
Mandatory - Declare names of the services you want to delete.
11+
.PARAMETER ForceIf
12+
Not Mandatory - Default is set to -WhatIf, to force deletion use this switch.
13+
14+
.EXAMPLE
15+
Remove-WindowsServiceCIM -ServiceNames Spooler, W32Time -ForceIf # To delete services without confirmation.
16+
17+
.NOTES
18+
v0.1.3
19+
#>
20+
[CmdletBinding()]
21+
param(
22+
[Parameter(Mandatory = $true, ValueFromPipeline = $true, Position = 0)]
23+
[string[]]$ServiceNames,
24+
25+
[Parameter(Mandatory = $false)]
26+
[switch]$ForceIf
27+
)
28+
BEGIN {
29+
Write-Verbose -Message "Removing Windows services..."
30+
}
31+
PROCESS {
32+
foreach ($ServiceName in $ServiceNames) {
33+
$Service = Get-Service -Name $ServiceName -ErrorAction SilentlyContinue
34+
if ($Service) {
35+
Write-Verbose -Message "Stopping service: $ServiceName"
36+
Stop-Service -Name $ServiceName -Force -WhatIf:$ForceIf.IsPresent
37+
$CimService = Get-CimInstance -ClassName Win32_Service -Filter "Name='$ServiceName'" -ErrorAction SilentlyContinue
38+
if ($CimService) {
39+
Write-Verbose -Message "Removing CIM instance for service: $ServiceName"
40+
$CimService | Remove-CimInstance -WhatIf:$ForceIf.IsPresent
41+
}
42+
else {
43+
Write-Warning -Message "CIM instance not found for service: $ServiceName"
44+
}
45+
}
46+
else {
47+
Write-Warning -Message "Service not found: $ServiceName"
48+
}
49+
}
50+
}
51+
END {
52+
$DeletedServices = Get-Service -Name $ServiceNames -ErrorAction SilentlyContinue
53+
if (-not $DeletedServices) {
54+
$output = $ServiceNames -join ', '
55+
Write-Output "Deleted services: $output"
56+
}
57+
}
58+
}

0 commit comments

Comments
 (0)