Kill Process on Remote Machine

I have a script I’m working on that asks for a machine name, and then produces a list of running processes on that machine. From there it asks the user I they want to kill a process on that machine. If they select Yes, it prompts the user to type in the name of the process and is supposed to kill it. Here is the code I have so far:

Get-Process -ComputerName $machine | Out-GridView
Write-Host
$message = Write-Host "Do you want to kill a process?" -foregroundcolor Green
Write-Host
$yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes"
$no = New-Object System.Management.Automation.Host.ChoiceDescription "&No"
$options = [System.Management.Automation.Host.ChoiceDescription[]][$yes, $no]
$result = $host.ui.PromptForChoice[$title, $message, $options, 0]
switch [$result]
{
    0{
    $process = Read-Host 'What is the process name?'
    Write-Host
    Write-Host "Killing Process..." -ForegroundColor Yellow
    Invoke-Command -ComputerName $machine {Stop-Process -ProcessName $process}

}
}

I’m not sure what parameter called ‘Name’ it is referring to but my eyes have gone cross-eyed looking at this so maybe I’m missing something obvious?

Please get into the habit of checking the parameters of cmdlets and functions with Get-Help. You won’t find a -ProcessName parameter. The correct parameters are -Name, -Id or -InputObject depending on the use case.

PS C:\> Get-Help Stop-Process

NAME
    Stop-Process

SYNTAX
    Stop-Process [-Id]  [-PassThru] [-Force] [-WhatIf] [-Confirm]  []

    Stop-Process -Name  [-PassThru] [-Force] [-WhatIf] [-Confirm]  []

    Stop-Process [-InputObject]  [-PassThru] [-Force] [-WhatIf] [-Confirm]  []

Another gotcha. The following line won’t work as expected:

Invoke-Command -ComputerName $machine {Stop-Process -ProcessName $process}

The curly brackets define a scriptblock. To get the value of variables outside of the scriptblock into it you will need to use the $Using: construct.

Invoke-Command -ComputerName $machine {Stop-Process -ProcessName $Using:process}

All the best to you,
Daniel