Powershell Stop-Process null param when called in foreach loop

I have the following tiny PowerShell script that is designed to kill some specific 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 get the following error:

It is not possible to associate an argument with the parameter "Id" because it is zero.

As far as I can see, the conveyor should not be interrupted by anything, so I'm not quite sure where I am going wrong.

+4
source share
2 answers

The script block does not receive $thisId , and it is set to null. Therefore stop-process gives an error. You can pass arguments to a script block, as mentioned by @Rynant.

Since all you do is get the processes and kill the processes matching your requirement, move the commands to the script block and execute this script block as a whole using Invoke-Command in the remote field:

 $script = {Get-Process -name uniRQBroker,uniRTE | stop-process -passthru | %{write-host killed pid $_.id}} invoke-command -script $script -computer $destPS 
+2
source

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

 Invoke-Command $destPS {Stop-Process $args} -ArgumentList $thisID 
+2
source

Source: https://habr.com/ru/post/1398688/


All Articles