Kill Process on Remote Machine

This topic contains 1 reply, has 2 voices, and was last updated by  Daniel Krebs 2 years, 5 months ago.

  • Author
    Posts
  • #24365

    Jesse Cleary
    Participant

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

    [img]http://i.imgur.com/hGez0zT.png[/img]

    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

    Daniel Krebs
    Moderator

    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

You must be logged in to reply to this topic.