Powershell有聚合/减少功能吗?

Geo*_*uer 26 powershell

我意识到存在相关的问题,但所有的答案似乎都是解决问题的核心问题.powershell是否有一个可以使用scriptblock将数组元素聚合为单个值的操作?这就是其他语言中所知的aggregatereducefold.

我可以很容易地自己编写它,但鉴于它是任何列表处理的基本操作,我会假设有一些我不知道的东西.

所以我正在寻找的是这样的

1..10 | Aggregate-Array {param($memo, $x); $memo * $x}
Run Code Online (Sandbox Code Playgroud)

Kei*_*ill 34

没有任何明显命名为Reduce-Object的东西,但你可以用Foreach-Object实现你的目标:

1..10 | Foreach {$total=1} {$total *= $_} {$total}
Run Code Online (Sandbox Code Playgroud)

BTW还没有Join-Object基于某些匹配属性合并两个数据序列.


man*_*lds 7

这是我想要开始一段时间的事情.看到这个问题,只写了一个pslinq(https://github.com/manojlds/pslinq)实用程序.现在是第一个也是唯一一个cmdlet Aggregate-List,可以像下面这样使用:

1..10 | Aggregate-List { $acc * $input } -seed 1
#3628800
Run Code Online (Sandbox Code Playgroud)

和:

1..10 | Aggregate-List { $acc + $input }
#55
Run Code Online (Sandbox Code Playgroud)

字符串反转:

"abcdefg" -split '' | Aggregate-List { $input + $acc }
#gfedcba
Run Code Online (Sandbox Code Playgroud)

PS:这更像是一个实验


Riv*_*art 6

最近遇到了类似的问题。这是一个纯粹的 Powershell 解决方案。不像 Javascript 版本那样处理数组和字符串中的数组,但也许是一个很好的起点。

function Reduce-Object {
    [CmdletBinding()]
    [Alias("reduce")]
    [OutputType([Int])]
    param(
        # Meant to be passed in through pipeline.
        [Parameter(Mandatory=$True,
                    ValueFromPipeline=$True,
                    ValueFromPipelineByPropertyName=$True)]
        [Array] $InputObject,

        # Position=0 because we assume pipeline usage by default.
        [Parameter(Mandatory=$True,
                    Position=0)]
        [ScriptBlock] $ScriptBlock,

        [Parameter(Mandatory=$False,
                    Position=1)]
        [Int] $InitialValue
    ) 

    begin {
        if ($InitialValue) { $Accumulator = $InitialValue }
    }

    process {
        foreach($Value in $InputObject) {
            if ($Accumulator) {
                # Execute script block given as param with values.
                $Accumulator = $ScriptBlock.InvokeReturnAsIs($Accumulator,  $Value)
            } else {
                # Contigency for no initial value given.
                $Accumulator = $Value
            }
        }
    }

    end {
        return $Accumulator
    }
}

1..10 | reduce {param($a, $b) $a + $b}
# Or
reduce -inputobject @(1,2,3,4) {param($a, $b) $a + $b} -InitialValue 2
Run Code Online (Sandbox Code Playgroud)


Pet*_*ter 5

如果你需要最大值,最小值,总和或平均值,你可以Measure-Object遗憾地使用它不会处理任何其他聚合方法.

Get-ChildItem | Measure-Object -Property Length -Minimum -Maximum -Average