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

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
A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
1,570 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. MotoX80 29,371 Reputation points

    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." 
    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 | Stop-Process -Force   ```
    1 person found this answer helpful.
    0 comments No comments

  2. Trevor Lacey 85 Reputation points
    $files = Get-ChildItem "C:\Path\To\Files" -Filter "*.exe" -Recurse -File
    0 comments No comments