Reputation: 85
I'm completely new to using PowerShell and computer programming in general. I'm trying to create a script that kills a process(firefox in this case) if it exceeds a working set of 10mb. I would like to do this using an if statement and also having a piping command included. So far I have this:
get-process|where-object {$_.ProcessName -eq"firefox"}
if ($_.WorkingSet -gt10000000)
{kill}
else
{"This process is not using alot of the computers resources"}
Can anyone help to fix this? Even though firefox is exceeding 10MB working set, the else statement is always reproduced.
Upvotes: 1
Views: 715
Reputation: 126842
You can filter the process in question by using the Name parameter (no need to use Where-Object
for this purpose) then pipe the objects to the Stop-Process
cmdlet. Notice the -WhatIf
switch, it shows what would happen if the cmdlet runs (the cmdlet is not run). Remove it to execute the cmdlet.
Get-Process -Name firefox |
Where-Object {$_.WorkingSet -gt 10mb} |
Stop-Process -WhatIf
Upvotes: 3
Reputation: 200373
You need to wrap the conditional in a loop:
Get-Process | ? { $_.ProcessName -eq 'firefox' } | % {
if ($_.WorkingSet -gt 10MB) {
kill $_
} else {
"This process is not using alot of the computers resources"
}
}
Otherwise the conditional would be evaluated independently from the pipeline, which means that the current object variable ($_
) would be empty at that point.
Upvotes: 4