4

I have the following tiny PowerShell script that's meant to kill some certain processes on a remote machine:

$destPS = "mywebserver1"
$brokerPIDs = Get-Process -ComputerName $destPS | ?{$_.processname -eq "uniRQBroker" -or $_.processname -eq "uniRTE"}
foreach ($process in $brokerPIDs){
    $thisId = $process.ID
    Write-Host "Killing PID $thisId"
    Invoke-Command $destPS {Stop-Process $thisId}
}

However, I'm getting the following error:

Cannot bind argument to parameter 'Id' because it is null.

As far as I can see, the pipeline shouldn't be interrupted by anything, so I'm not quite sure where I'm going wrong.

Mark Henderson
  • 2,586
  • 1
  • 33
  • 44

2 Answers2

3

The script block doesn't get the $thisId and that is set to null. So stop-process gives the error. You can pass the arguments to the script block like @Rynant mentions.

Since all you are doing is to get the processes and kill processes that match your requirement, move the commands into a script block and execute that scriptblock as whole using Invoke-Command on the remote box:

$script = {Get-Process -name uniRQBroker,uniRTE  | stop-process -passthru | %{write-host killed pid $_.id}}

invoke-command -script $script -computer $destPS
manojlds
  • 290,304
  • 63
  • 469
  • 417
  • Thanks. I really like your compressed version of the script too, far fewer remote calls to slow the system down (it can be run over a high-latency link). – Mark Henderson Feb 27 '12 at 22:34
2

You need to pass the variable thisId to the scriptblock as an argument (Invoke-Command executes the scriptblock in a separate temporary session when running against a remote computer, hence local variables are no longer in scope). Try it as:

Invoke-Command $destPS {Stop-Process $args} -ArgumentList $thisID
Rynant
  • 23,153
  • 5
  • 57
  • 71