I created a script that disables Windows services.
Their number may exceed 50 services.
There are some services whose name goes back to previous versions of Windows; As these services changed their name in newer versions of Windows. So I used if
: If the service name is present in $Services, it will be disabled.
With all this, the script does not work.. what is the reason?
I suspect in "if($Service.Name)
"
$Services = @(
"mpssvc"
"wscsvc"
"clipSVC"
#There are more services, but it's not necessary to show them here.
)
foreach ($Service in Services) {
if($Service.Name -NotIn $Services)
{
Stop-Service $Service
Set-Service $Service -StartupType Disabled
}
}
CodePudding user response:
Let's walk through the code and see where the problem is.
# An array containing service names
$Services = @(
"mpssvc"
"wscsvc"
"clipSVC"
#There are more services, but it's not necessary to show them here.
)
# Loop through the array. Pick a name one by one.
foreach ($Service in Services) {
# Compare the array contents with service's name. Here's the catch
if($Service.Name -NotIn $Services)
So, what's wrong? It's the $Service.Name
. Since $Service
is the variable containing the current item from the $services
collection, it doesn't have a .Name
property. What's more, the code is checking one by one if the collection contains all of its members. Which it always will.
To achieve disabling of wanted services, get a list of services and comnpare that to the list of services to disable. Like so,
# An array containing service names
$ServicesToDisable = @(
"mpssvc"
"wscsvc"
"clipSVC"
)
# Get all running services
$RunningServices = Get-Service | ? {$_.Status -eq "Running"}
# Loop through running services. See if it is in the disable array
foreach($s in $RunningServices) {
if($s.Name -in $ServicesToDisable) {
Set-Service -Startuptype Disalbed -Name $s.Name
}
}