3

我有以下代码:

function f()
{
    begin{$count=0}
    process{$count+=10}
    end{$count}
}
1..10|f # OK
1..10|%{
    begin{$count=0}
    process{$count+=10}
    end{$count}
} # Error

第一个“f”调用成功,而 %{} 块显示错误:

100
% : The script block cannot be invoked because it contains more than one clause. The Invoke() method can only be used on script blocks that contain a single clause.
At D:\Untitled1.ps1:13 char:7
+ 1..10|%{
+       ~~
    + CategoryInfo          : InvalidOperation: (:) [ForEach-Object], PSInvalidOperationException
    + FullyQualifiedErrorId : InvalidOperation,Microsoft.PowerShell.Commands.ForEachObjectCommand

但为什么?ForEach-Object不支持begin//块processend

4

3 回答 3

7

ForEach-Object将各个块作为单独的命名参数。

在你的情况下,那将是:

1..10 |ForEach-Object -Begin {$count=0} -Process {$count+=10} -End {$count}

这在帮助文件中有很好的记录 - 来自Get-Help ForEach-Object -Parameter *

-Begin <ScriptBlock>
    Specifies a script block that runs before processing any input objects.

    Required?                    false
    Position?                    named
    Default value                None
    Accept pipeline input?       false
    Accept wildcard characters?  false


-End <ScriptBlock>
    Specifies a script block that runs after processing all input objects.

    Required?                    false
    Position?                    named
    Default value                None
    Accept pipeline input?       false
    Accept wildcard characters?  false

<# ... #>

-Process <ScriptBlock[]>
    Specifies the operation that is performed on each input object. Enter a script
    block that describes the operation.

    Required?                    true
    Position?                    1
    Default value                None
    Accept pipeline input?       false
    Accept wildcard characters?  false
于 2015-06-25T08:11:11.430 回答
1

作为附录,如果您想构建代码以便于阅读,这只是一个小点。延续勾号(“`”)很重要——因为我刚刚发现自己要付出一些代价!

Get-Content -Path $SelectedFiles | ForEach-Object `
-Begin {
 #- Do Begin stuff -----
 } `
-Process {
#- Do Process stuff
} `
-End {
#- Do End stuff
}
#- EndOf: ForEach is here -----
#- NB! Continuation tick "`" must be preceded by space & be LAST character on line!!!!!

为了在 ISE 中提供帮助,正确识别时参数(开始、过程、结束)的颜色应该与其他参数(我的参数是黑色)相同。在 ISE 中使用上面的代码,在勾号后放一个空格,在勾号之前不要有空格,等等。我没有意识到“空格”有多么重要 - 咧嘴笑!祝你好运!希望这对像我这样的初学者有所帮助。

于 2017-05-01T12:32:17.447 回答
1

一件很酷的事情是,您可以在不指定参数的情况下执行此操作,并且在幕后使用 -process 和 -remainingscripts 即可。

1..10 | ForEach {$count=0} {$count+=10} {$count}

100
于 2019-10-22T18:31:05.297 回答