Powershell Scripts to Stop all Services running from a dir and it's subdirs, and a script to do the same with running processes

David Holland 0 Reputation points
2023-10-25T21:00:44.9566667+00:00

I am looking to stop all services running from a particular directory and its subdirectories and also terminate all active processes after that that are running from that same directory. 

One PowerShell snippet for the services and then one for the processes.

Here is what I have so far for the processes, but it only does it for one dir, not all its subdirectories:

$files = gci "C:\Path\To\Files" -Filter "*.exe"

foreach($file in $files){
    Get-Process | 
    Where-Object {$_.Path -eq $file.FullName} | 
    Stop-Process -WhatIf
}
PowerShell
PowerShell
A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
2,613 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. MotoX80 34,516 Reputation points
    2023-10-26T02:58:12.2766667+00:00

    Since you want to include subfolders, you don't need to look at every .exe file. You can just check the exe path for the process and see if it starts with your folder name. That will run faster because it only needs to look at the processes one time and not every time for each exe file.

    I did it like this.

    $folder = "C:\WINDOWS\System32\Openssh"
    $s = Get-CimInstance -Class Win32_Service -Filter 'State="Running"' | ForEach-Object {
        if ($_.PathName.tolower().contains($folder.ToLower())) {    # insure no issue with case 
            $_.Name       # just return the service name 
        }    
    }
    
    "I found these services." 
    $s 
    Get-Service $s | Stop-Service -Force 
    $p = Get-Process  | ForEach-Object {
        if ($_.Path) {                                               # some processes like wininit don't have a path  
            if ($_.Path.tolower().contains($folder.ToLower())) {     # insure no issue with case 
                $_       # return the process object and not just the name    
            }
        }    
    } 
    "I found these processes." 
    $p
    $p | Stop-Process -Force   ```
    
    
    1 person found this answer helpful.
    0 comments No comments

  2. Trevor Lacey 85 Reputation points
    2023-10-25T23:33:47.8933333+00:00
    $files = Get-ChildItem "C:\Path\To\Files" -Filter "*.exe" -Recurse -File
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.