我不能在ForEach-Object中使用begin / process / end块?

时间:2015-06-25 07:04:59

标签: powershell foreach scriptblock

我已获得以下代码:

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 / process / end块?

3 个答案:

答案 0 :(得分:5)

1..10 |ForEach-Object -Begin {$count=0} -Process {$count+=10} -End {$count} 将各个块作为单独的命名参数。

在你的情况下,那将是:

-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

帮助文件中有详细记录 - 来自Get-Help ForEach-Object -Parameter *

student

答案 1 :(得分:0)

作为附录,如果您希望构建代码以便于阅读,那么这只是一个小问题。延续时间刻度(&#34;`&#34;)很重要 - 因为我刚刚发现了自己的一些费用!

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中提供帮助,在正确识别时,参数(Begin,Process,End)的颜色应与其他参数(我的参数为黑色)相同。在ISE中使用上面的代码,在打勾后放置一个空格,在打勾之前没有空格等。 我没有意识到“空间”的重要性。可能 - 咧嘴笑! 祝好运!希望这有助于像我这样的另一个初学者。

答案 2 :(得分:0)

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

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

100