PowerShell: the mysterious -RemainingScripts parameter of ForEach-Object

前端 未结 5 2105
闹比i
闹比i 2021-02-08 00:21

Short question: anyone has detailed information on -RemainingScripts parameter of ForEach-Object?

Long question:

I just started

5条回答
  •  你的背包
    2021-02-08 00:46

    I believe -remainingscripts (with attribute 'ValueFromRemainingArguments') is to enable an idiom like this from Windows Powershell in Action, an idiom which almost nobody knows (20% of Powershell is only documented in that book):

    Get-ChildItem | ForEach {$sum=0} {$sum++} {$sum}
    

    The blocks end up acting like begin process end. The parameters being used are actually -process and -remainingscripts.

    trace-command -name parameterbinding { Get-ChildItem | ForEach-Object {$sum=0} {$sum++} {$sum} } -PSHost
    

    That trace-command seems to confirm this.

    Here's a simple demo of ValueFromRemainingArguments with scriptblocks.

    function remaindemo {
      param ($arg1,  [Parameter(ValueFromRemainingArguments)]$remain)
      & $arg1
      foreach ($i in $remain) {
        & $i
      }
    }
    
    remaindemo { 'hi' } { 'how are you' } { 'I am fine' }
    

    Other commands with ValueFromRemainingArguments parameters:

    gcm -pv cmd | select -exp parametersets | select -exp parameters |
      where ValueFromRemainingArguments | 
      select @{n='Cmdname';e={$cmd.name}},name
    
    Cmdname        Name
    -------        ----
    ForEach-Object RemainingScripts
    ForEach-Object ArgumentList
    Get-Command    ArgumentList
    Get-Command    ArgumentList
    Join-Path      AdditionalChildPath
    New-Module     ArgumentList
    New-Module     ArgumentList
    Read-Host      Prompt
    Trace-Command  ArgumentList
    Write-Host     Object
    Write-Output   InputObject
    

提交回复
热议问题