代码之家  ›  专栏  ›  技术社区  ›  Sint

传递/管道/循环从get process到powershell poshinternals脚本的所有进程

  •  1
  • Sint  · 技术社区  · 6 年前

    我将如何通过GET进程将所有进程传递给另一个PosiScript脚本?

    伪码

    for each process in matchingprocesses:
      myScript(process)
    

    计划使用集工作集脚本: https://www.powershellgallery.com/packages/PoshInternals/1.0/Content/Set-WorkingSetToMin.ps1

    这是伟大的,因为只有一个记事本+ +过程:

    get-process notepad++ | Set-WorkingSetToMin 
    

    然而,对于VS代码,这只得到第一个代码过程,而忽略其余的:

    get-process code | Set-WorkingSetToMin
    

    如何将匹配特定名称的每个进程管道化到powershell脚本?

    另一种方法是修改POSSHYNTIALS脚本以接受多个进程:

    # 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 回复  |  直到 6 年前
        1
  •  1
  •   Sint    6 年前

    您可以添加WHERE子句以拉出所需的进程,然后设置设置为工作集SETTIMIN的管道。下面是一个例子,但是根据需要进行调整,以准确地拉动您正在寻找的内容。

    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)
    }
    

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