Home > OS >  Fetching value of processId from list of process Ids
Fetching value of processId from list of process Ids

Time:03-02

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.

CodePudding user response:

Maybe you could do it this way, I believe outputting an object to the console would be more readable. The only change you need to do is move the Stop-Process inside the if condition.

$lockedFile = 'defineThisVariable'
Get-Process | ForEach-Object {
    if($_.Modules.FileName.where({$_ -eq $lockedFile})) {
        # This is the ouput object to the console
        [pscustomobject]@{
            Process = $_.Name
            PID     = $_.id
        }
        # Here you stop the Process, you can add
        # `-Verbose` for more output to console
        Stop-Process -Id $_.Id
    }
}
  • Related