'Fetching value of processId from list of process Ids

I am running the below cmdlet to get the process ids used by a file:

Get-Process | foreach{$processVar = $_;$_.Modules | foreach{if($_.FileName -eq $lockedFile){$processVar.Name + " PID:" + $processVar.id}}}

The above cmdlet is generating the output process1 PID:5260

Now, I need to pipe the cmdlet so as to kill the above process id for which I have written below cmdlet:

Get-Process | foreach{$processVar = $_;$_.Modules | foreach{if($_.FileName -eq $lockedFile){$processVar.Name + " PID:" + $processVar.id}}} | Stop-Process $processVar.id

However, it is not stopping the process.

I basically want to print out the process name and process id and then kill the process.

The process name and process id are already printing out correctly but need help to pipe the process id into the cmdlet and then kill the process.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source