您在处理管道输入时使用
begin
、
process
和
end
块。
begin
块用于预处理,并在处理输入开始之前运行一次。
end
块用于后处理,并在处理输入完成后仅运行一次。如果您想要在
end
块以外的任何地方调用函数,则需要在
begin
块中定义它(在
process
块中反复重新定义会浪费资源,即使您在
begin
块中没有使用它)。
[CmdletBinding()]
param(
[String]$Value
)
BEGIN {
Function f() {
param([String]$m)
Write-Host $m
}
f("Begin")
}
PROCESS {
f("Process:" + $Value)
}
END {
f("End")
}
引用自about_Functions
:
Piping Objects to Functions
Any function can take input from the pipeline. You can control how a function processes input from the pipeline using Begin, Process, and End keywords. The following sample syntax shows the three keywords:
function <name> {
begin {<statement list>}
process {<statement list>}
end {<statement list>}
}
The Begin statement list runs one time only, at the beginning of the function.
The Process statement list runs one time for each object in the pipeline. While the Process block is running, each pipeline object is assigned to the $_ automatic variable, one pipeline object at a time.
After the function receives all the objects in the pipeline, the End statement list runs one time. If no Begin, Process, or End keywords are used, all the statements are treated like an End statement list.
如果您的代码不处理管道输入,则可以完全删除
begin
、
process
和
end
块,并将所有内容放在脚本主体中:
[CmdletBinding()]
param(
[String]$Value
)
Function f() {
param([String]$m)
Write-Host $m
}
f("Begin")
f("Process:" + $Value)
f("End")
编辑:如果你想在脚本末尾定义 f
的函数,你需要将其余的代码定义为一个 worker/main/whatever 函数,并在脚本末尾调用该函数,例如:
[CmdletBinding()]
param(
[String]$Value
)
function Main {
[CmdletBinding()]
param(
[String]$Param
)
BEGIN { f("Begin") }
PROCESS { f("Process:" + $Param) }
END { f("End") }
}
Function f() {
param([String]$m)
Write-Host $m
}
Main $Value
BEGIN
块内定义它。 - user4003407