Skip to content
mnaoumov.dev
Go back

Kill Bill _W conhost

Sometimes we can have dozens of conhost.exe processes that eating our memory.

What is conhost?

Basically it is a process that runs at the same time with any console application you are running.

Learn more

What if we want to kill them all? We go to PowerShell and type

Stop-Process -Name conhost

Oops? What happened? It also stopped our PowerShell process.

Ok, then, we want to stop all conhost process except the one which corresponds to the PowerShell.

After some checks and using the article linked above, I’ve found that the only reliable way to find out which conhost process corresponds to which console application, is to check their creation time.

function Get-CorrespondingConhostProcessId
{
    param
    (
        $processId = $PID
    )

    $powerShellCreationDate = Get-ProcessCreationDate $processId

    $conhostProcessIds = Get-Process -Name conhost | `
        Select-Object -ExpandProperty Id

    foreach ($conhostProcessId in $conhostProcessIds)
    {
        $conhostCreationDate = Get-ProcessCreationDate $conhostProcessId

        $diff = $conhostCreationDate - $powerShellCreationDate

        if ([Math]::Abs($diff.TotalSeconds) -lt 1)
        {
            return $conhostProcessId
        }
    }
}

function Get-ProcessCreationDate
{
    param
    (
        [int] $ProcessId
    )

    $wmiDate = Get-WmiObject -Class Win32_Process -Filter "ProcessId = $ProcessId" | `
        Select-Object -ExpandProperty CreationDate

    [System.Management.ManagementDateTimeConverter]::ToDateTime($wmiDate)
}

Using functions we can write function

function Kill-Conhost
{
    $correspondingConhostProcessId = Get-CorrespondingConhostProcessId
    Get-Process -Name conhost | `
        Where-Object { $_.Id -ne $correspondingConhostProcessId  } | `
        Stop-Process
}

Voila!


Share this post on:

Previous Post
where.exe PowerShell alternative
Next Post
git hook proxy