lit
lit

Reputation: 16256

Nested function inside a function with begin/process/end blocks?

Is it possible to have a nested function inside a function containing begin/process/end blocks? The first error reported is:

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:\src\cut\f1.ps1:13 char:5
+     begin { Write-Verbose "initialize stuff" }
+     ~~~~~
    + CategoryInfo          : ObjectNotFound: (begin:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

Here is the code in question.

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:\src\cut\cut-man.txt' | f1 -Path '.\cut-man.txt'

The function may have a dozen or more parameters. If I cannot nest the function, I will need to create another function and duplicate passing the parameters or use global variables. I do not want to use global variables if possible. How can this be done?

Upvotes: 2

Views: 2175

Answers (1)

BahyGHassan
BahyGHassan

Reputation: 126

Yes it is possible to create nested function but you must stick with the structure of the function section which is like this:

function ()
{
   param()
   begin{}
   process{}
   end{}
}

you cant write anything between param,begin,process and end sections. so to write your second function you have two options. 1- you can write the second function outside the first function and it works like magic. 2- if you need to test the option of nested functions, you can write your second function either in begin section or in the start of the process section as following:

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:\src\cut\cut-man.txt' | f1 -Path '.\cut-man.txt'  -Verbose

Upvotes: 5

Related Questions