是否可以在包含开始/进程/结束块的函数中有一个嵌套函数?报告的第一个错误是:
begin : The term 'begin' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if
a path was included, verify that the path is correct and try again.
At C:srccutf1.ps1:13 char:5
+ begin { Write-Verbose "initialize stuff" }
+ ~~~~~
+ CategoryInfo : ObjectNotFound: (begin:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
这是有问题的代码。
function f1 (
[Parameter(Mandatory=$false, ValueFromPipeline=$true)]
[array]$Content
,[Parameter(Mandatory=$false, ValueFromPipeline=$false, Position=0)]
[string[]]$Path
)
{
function a([Parameter(Mandatory=$true)][string]$s)
{
"=== a === $s"
}
begin { Write-Verbose "initialize stuff" }
process {
Write-Verbose "process stuff"
a($Content)
}
end { Write-Verbose "end stuff" }
}
Get-Content -Path 'C:srccutcut-man.txt' | f1 -Path '.cut-man.txt'
该函数可能有十几个或更多参数。如果我无法嵌套函数,我将需要创建另一个函数并重复传递参数或使用全局变量。如果可能的话,我不想使用全局变量。如何做到这一点?
是的,可以创建嵌套函数,但您必须坚持函数部分的结构,如下所示:
function ()
{
param()
begin{}
process{}
end{}
}
你不能在参数,开始,过程和结束部分之间写任何东西。 因此,要编写第二个函数,您有两种选择。 1-您可以在第一个函数之外编写第二个函数,它就像魔术一样工作。 2-如果您需要测试嵌套函数的选项,则可以在开始部分或流程部分的开头编写第二个函数,如下所示:
function f1 (
[Parameter(Mandatory=$false, ValueFromPipeline=$true)]
[string]$Content
,[Parameter(Mandatory=$false, ValueFromPipeline=$false, Position=0)]
[string[]]$Path
)
{
begin
{
Write-Verbose "initialize stuff"
function a([Parameter(Mandatory=$true)][string]$s)
{
"=== a === $s"
}
}
process
{
Write-Verbose "process stuff"
a($Content)
}
end
{
Write-Verbose "end stuff"
}
}
Get-Content -Path 'C:srccutcut-man.txt' | f1 -Path '.cut-man.txt' -Verbose