How can I search for an PID for using an explicit handlename?

77 Views Asked by At

My goal is to search all Process from every user and search if someone is using an explicit dll that I already know at the start of my script. And when a User is running a Procces in which my Handlename is running I want to kill this process.

I already know under which processname the handle would be running, that would be: msaccess

my Idea was to search for the process of msaccess like this:

$processName = "msaccess.exe"
$handleNamePath = "C:\\Program Files (x86)\\Sage\\Sage 100\\9.0\\Shared\\GEKKO.HPGebote.dll"

$process = Get-WmiObject Win32_Process | Where-Object {$_.Name -eq $processName} | Select-Object -ExpandProperty ProcessId

# Loop through all processes
foreach ($process in (Get-Process)) {
    # Get all handles for the process
    $handles = $process | Select-Object -ExpandProperty Handles

    # Check if any handle matches the search pattern
    foreach ($handle in $handles) {
Write-Output "Found handle $($handle.HandleName) in process $($process.Name)"

        if ($handle.HandleName -like $handleNamePath) {
            Write-Output "Found handle $handleNamePath in process $($process.Id)"
            # Kill the process
            $process.Kill()
        }
    }
}

At the end I want an similiar Output like that in the Ressource Monitor: Example

I tried this too, to loop through every process and look every children through but for some reason my dll path will not be found?

$parentProcesses = Get-Process | Where-Object {$_.ParentProcessId -eq 0} 

foreach ($parentProcess in $parentProcesses) {
    Write-Host "Elternprozess Name: $($parentProcess.ProcessName), ID: $($parentProcess.Id), Path: $($parentProcess.Path)"

    $childProcesses = Get-Process | Where-Object {$_.ParentProcessId -eq $parentProcess.Id}

    foreach ($childProcess in $childProcesses) {
        if ($childProcess.Path -like "C:\\Program Files (x86)\\Sage\\Sage 100\\9.0\\Shared\\GEKKO.HPGebote.dll") {
            Write-Host "    Kindprozess Name: $($childProcess.ProcessName), ID: $($childProcess.Id), Path: $($childProcess.Path)"
        }
    }
}

Here is a look on my Task Manager, the selected Process is my dll and I want it to find:

Example

but thats not working like I want, im quite new to this, has anyone an Idea or an advise for me How I could achieve that?

0

There are 0 best solutions below