Kill all processes running from a directory and it's subdirectories

I am looking to delete all processes that are running from a certain directory and it’s subdirectories.

I have this code that works great for a directory, but I cannot find a way to have it iterate through all the subdirectories also.

For bonus points it’d be spectacular to stop all services that are running from that directory first… but as a separate PowerShell snippet.

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

foreach($file in $files){
    Get-Process | 
    Where-Object {$_.Path -eq $file.FullName} | 
    Stop-Process -WhatIf
}

Please do not use aliasses in scripts or in forums as it makes your code harder to read.

You should ALWAYS read the help for the cmdlets you’re about to use COMPLETELY INCLUDING THE EXAMPLES to learn how to use them!!

How about

$files = Get-ChildItem -Path "C:\Path\To\Files" -Filter "*.exe" -Recurse

?? :man_shrugging:t3:

For bonus points: Instead of using a single plural “s” you should make it more obvious that a variable refers an array … something like $FileList or $FileArray.

?? I don’t get it. What do you mean? :thinking:

For bonus points: You approach is very inefficient. You query ALL services again and again for each individual executable in your folder (and subfolders). I’d collect the file list and the list of processes in advance and compare them with Compare-Object. :point_up:t3: :wink:

You could also just call Get-Process once and look at .MainModule.FileName and match to the directory you are targetting. For sub directories as long as the path contains the root directory you can target all sub-directories the same way.