function - 如何在 CmdletBinding() 脚本中定义函数?

标签 function powershell pipeline powershell-cmdlet

我正在编写一个脚本,我想使用 PowerShell 的 CmdletBinding() 。 有没有办法在脚本中定义函数?当我尝试时,PowerShell 提示“表达式或语句中出现意外的 token 'function'”

这是我正在尝试做的事情的简化示例。

[CmdletBinding()]
param(
    [String]
    $Value
)

BEGIN {
    f("Begin")
}

PROCESS {
    f("Process:" + $Value)
}

END {
    f("End")
}

Function f() {
    param([String]$m)
    Write-Host $m
}

就我而言,编写模块是浪费开销。这些功能只需对这一脚本可用。我不想弄乱模块路径或脚本位置。我只想运行一个其中定义了函数的脚本。

最佳答案

当您的代码应该处理管道输入时,您可以使用 beginprocessend block 。 begin block 用于预处理,并在输入处理开始之前运行一次。 end block 用于后处理,并在输入处理完成后运行一次。如果您想在 end block 之外的任何地方调用函数,您可以在 begin block 中定义它(在 process block 会浪费资源,即使您没有在 begin block 中使用它)。

[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.

<小时/>

如果您的代码不处理管道输入,您可以完全删除 beginprocessend block ,并将所有内容放入脚本中正文:

[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

关于function - 如何在 CmdletBinding() 脚本中定义函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30737491/

相关文章:

javascript - 如何将常量放入函数中而不使其成为全局常量

javascript - 函数仅从 $(function(){ 调用一次

powershell - 当环境变量在路径中时,PowerShell错误

powershell - 如何让 Windows Powershell Get-ItemProperty 只显示我想要的属性?

powershell - 如何在 PowerShell 中通过管道传输二进制数据

asp.net-mvc - 日志 MVC 管道

javascript - Angular 7 ng build,registry.registerUriHandler 不是 bitbucket 管道中的函数

r - 基于重要性的变量缩减

python - 如何在python2.7中的函数中发送变量

performance - 为什么 PostgreSQL 多次调用我的 STABLE/IMMUTABLE 函数?