Kill Process on Remote Machine

Welcome Forums General PowerShell Q&A Kill Process on Remote Machine

This topic contains 1 reply, has 2 voices, and was last updated by

3 years, 10 months ago.

  • Author
  • #24365

    Points: 0
    Rank: Member

    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
    $message = Write-Host "Do you want to kill a process?" -foregroundcolor Green
    $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]
        $process = Read-Host 'What is the process name?'
        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?

  • #24366

    Points: 24
    Team Member
    Rank: Member

    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
        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,

The topic ‘Kill Process on Remote Machine’ is closed to new replies.

denizli escort samsun escort muğla escort ataşehir escort kuşadası escort