Friday 5 April 2013

Stopping a process with Powershell and the Out-GridView

Powershell can display a nice menu where the user can select e.g. a single or a multiple element in an arbitrary gridview, with the cmdlet Out-GridView. Let's see how this can be done to support stopping a single process of which the user chooses to stop. Of course, this is already available in Task Manager, but it is always nice to see that Powershell can give us a dedicated way of doing this also.

Here is the script for doing this, in the function Stop-SelectedProcess:

            
function Stop-SelectedProcess(){            
            
    Write-Host Select the process to stop ...            
    Start-Sleep 2            
                
    $selectedProcess = $null             
    Get-Process | Out-GridView -OutputMode Single -Outvariable selectedProcess            
                
    if ($selectedProcess -eq $null -or $selectedProcess.Count -eq 0)             
    {            
        return;            
    }             
            
    Stop-Process $selectedProcess            
            
}            
            
Stop-SelectedProcess
Make note how the Out-GridView cmdlet which we pipe the result from Get-Process to is specified to have an -OutputMode of single (i.e. choose one item at a time)and a -OutVariable also set, also note the missing $-sign after -OutVariable, this is correct. This shows how we can present the user with a nice menu to choose for while running the command. This is easier than asking the user to select a process to stop by e.g. PID or #-line number.

This is just another example of how modern as a scripting language Powershell really is.

Word of caution at the end - never stop a process you are not sure of what runs. I stopped the process smss process the other day, because I thought it was Sql Management Studio. Needless to say, I experienced my first BSOD in Windows 8 ..

Screenshot of the action:

Share this article on LinkedIn.

1 comment:

  1. Perhaps a better name could be Select-ProcessToStop ...

    ReplyDelete