通过/管道/循环所有过程,从Get-Process到Powershell PoshInternals脚本

时间:2018-06-20 14:35:39

标签: windows powershell loops process

我如何将具有匹配特定进程名称的Get-Process的所有进程逐个传递给另一个PowerShell脚本?

伪代码

for each process in matchingprocesses:
  myScript(process)

计划的用法Set-WorkingSetToMin脚本:https://www.powershellgallery.com/packages/PoshInternals/1.0/Content/Set-WorkingSetToMin.ps1

这非常有用,因为只有一个notepad ++进程:

get-process notepad++ | Set-WorkingSetToMin 

但是,对于VS Code而言,这只会获得第一个代码过程,而忽略其余的过程:

get-process code | Set-WorkingSetToMin

如何将与某个名称匹配的每个进程传递给Powershell脚本?

替代方法是修改PoshInternals脚本以接受多个进程:

# Dont run Set-WorkingSet on sqlservr.exe, store.exe and similar processes
# Todo: Check process name and filter
# Example - get-process notepad | Set-WorkingSetToMin 
Function Set-WorkingSetToMin {
    [CmdletBinding()]
    param(
    [Parameter(ValueFromPipeline=$True, Mandatory=$true)]
    [System.Diagnostics.Process] $Process
    )

if ($Process -ne $Null)
{
    $handle = $Process.Handle
    $from = ($process.WorkingSet/1MB) 
    $to = [PoshInternals.Kernel32]::SetProcessWorkingSetSize($handle,-1,-1) | Out-Null
    Write-Output "Trimming Working Set Values from: $from"

} #End of If
} # End of Function

在一行中没有额外变量的答案:

foreach ($process in Get-Process myprocessname) { Set-WorkingSetToMin ($process) }

1 个答案:

答案 0 :(得分:1)

您可以添加where子句以仅提取所需的进程,然后通过管道将其设置为Set-WorkingSetToMin。下面是一个示例,但可以根据需要进行调整以准确提取所需的内容。

get-process | where {$_.ProcessName -like "*code*"} | Set-WorkingSetToMin

更新: 我明白您在说什么,问题不在于发送的进程集,而在于它们在那里后如何处理。为了解决这个问题,您可以设置一个等于过程集的变量,然后遍历它们,每次都调用cmdlet。像这样:

$processes = get-process | where {$_.ProcessName -like "code"} | Set-WorkingSetToMin

foreach ($process in $processes)
{
    Set-WorkingSetToMin ($process)
}

ANSWER感谢Landon的帮助:foreach ($process in Get-Process myprocessname) { Set-WorkingSetToMin ($process) }