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