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!

Advertisements

About mnaoumov

Senior .NET Developer in Readify
This entry was posted in Uncategorized and tagged . Bookmark the permalink.

One Response to Kill Bill ^W conhost

  1. Pingback: Answer: (When) is CONHOST.EXE actually necessary? #it #computers #programming | StackCopy

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s