-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDisableEnabledScript.ps1
More file actions
45 lines (41 loc) · 1.76 KB
/
DisableEnabledScript.ps1
File metadata and controls
45 lines (41 loc) · 1.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# Define services to disable
#example: $ServicesToDisable = ("RasAuto","RpcLocator","upnphost","wsa_proxy")
$ServicesToDisable = ("wsa_proxy")
$ScriptName = "Service Disable Script"
$LogName = "Application"
# Create a new event source if it doesn't exist
try {
if (![System.Diagnostics.EventLog]::SourceExists($ScriptName)) {
New-EventLog -LogName $LogName -Source $ScriptName
}
}
catch {
# If we can't create the event source, we'll fall back to System log with System source
$ScriptName = "System"
$LogName = "System"
}
foreach ($Service in $ServicesToDisable) {
try {
$serviceStatus = Get-Service $Service -ErrorAction Stop
if ($serviceStatus.StartType -ne "Disabled") {
# Attempt to disable the service
Set-Service -Name $Service -StartupType Disabled -ErrorAction Stop
Write-EventLog -LogName $LogName -Source $ScriptName -EventId 1000 -EntryType Information `
-Message "Successfully disabled service: $Service"
}
else {
Write-EventLog -LogName $LogName -Source $ScriptName -EventId 1001 -EntryType Information `
-Message "Service $Service is already disabled. No action needed."
}
}
catch {
if ($_.Exception.Message -like "*Cannot find any service with service name*") {
Write-EventLog -LogName $LogName -Source $ScriptName -EventId 1002 -EntryType Information `
-Message "Service $Service does not exist on this system. No action needed."
}
else {
Write-EventLog -LogName $LogName -Source $ScriptName -EventId 1003 -EntryType Error `
-Message "Error processing service $Service. Error: $($_.Exception.Message)"
}
}
}