I want to find out how many java PIDs are running in order to stop them, put the values into an array, run it inside a loop and kill each process
Therefore I use the command
$a=ps | Where-Object -Property ProcessName -EQ -Value 'Java'`
Which shows me the following result:
Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) **Id** ProcessName
------- ------ ----- ----- ----- ------ -- -----------
661 51 748504 421716 -282 **2008** java
331 22 358464 135808 -525 **14060** java
But I am stuck regarding how to extract the Id column values , in order to loop them later
Any help would be appreciated,
Many thanks
CodePudding user response:
As Santiago Squarzon commented, you can directly pipe the output of Get-Process
(alias ps
) to Stop-Process
:
ps Java | Stop-Process
In case you want to list the killed processes, you can use -PassThru
:
ps Java | Stop-Process -PassThru
So in most cases you don't even need to write a loop.
If you still have a use case where you need to explicitly loop over the process IDs, you can do it as suggested by mclayton, using member-access enumeration:
$proc = ps Java
foreach( $pid in $proc.Id ) {
# do something with $pid
"PID: $pid"
}
# ...or even shorter:
(ps Java).Id.ForEach{
"PID: $_"
}
CodePudding user response:
@Santiago Squarzon, @mclayton, @zett42 . Many thanbks for your time and colaboration