powershellmutexhandle

Close Mutant handle


I found handle mutex using Process Explorer.

enter image description here

I can close it with this programm, then i'm able to launch second instance of PrivodBondar.exe. With chatGPT help I wrote powershell script which closing this mutex:

Import-Module NtObjectManager

# Define the name of the mutant (mutex) handle to close
$mutexName = "\Sessions\26\BaseNamedObjects\PrivodBondar_tmdi"

# Get the list of all processes and iterate to find the handle
$allProcesses = Get-Process

foreach ($process in $allProcesses) {
    try {
        # Get all handles in the process
        $handles = Get-NtHandle -ProcessId $process.Id -ErrorAction SilentlyContinue
        
        # Look for the handle matching the specified mutex name
        foreach ($handle in $handles) {
            if ($handle.Name -eq $mutexName) {
                Write-Host "Found mutex handle in process $($process.ProcessName) (PID: $($process.Id)). Closing handle..."
                
                # Close the handle
                $handle.Close()
                Write-Host "Handle closed successfully."
                break
            }
        }
    }
    catch {
        # Handle any access exceptions
        Write-Host "Could not access handles for process $($process.ProcessName) (PID: $($process.Id)) due to permissions."
    }
}

but faced with permissions issue.

.\close_mutex.ps1
Found mutex handle in process PrivodBondar (PID: 71168). Closing handle...
Could not access handles for process PrivodBondar (PID: 71168) due to permissions.

How to close this mutex using script? PS I launched powershell with Administrator privilege


Solution

  • A glance at the NtObjectManager source code suggests the method name is CloseHandle, not Close:

    # Look for the handle matching the specified mutex name
    foreach ($handle in $handles) {
        if ($handle.Name -eq $mutexName) {
            Write-Host "Found mutex handle in process $($process.ProcessName) (PID: $($process.Id)). Closing handle..."
            
            # Close the handle
            $handle.CloseHandle()
            Write-Host "Handle closed successfully."
            break
        }
    }
    

    Additionally, you might want to restructure your try/catch block so that you can tell permission-related errors apart from other types of errors:

    try {
        # ...
    }
    catch [System.UnauthorizedAccessException] {
        Write-Host "Could not access handles for process $($process.ProcessName) (PID: $($process.Id)) due to permissions."
    }
    catch {
        Write-Host "Unexpected error: $_"
    }