Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Disable exists Winsows services – PowerShell

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
    }   
}

>Solution :

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
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading