dan-gph
dan-gph

Reputation: 16909

Calling functions from Process blocks

I would like to call a particular function from within both the Process and End blocks in my PowerShell script. Here is the minimal code:

# MyScript.ps1

function MyFunc
{
    "hello"
}

Begin 
{
}

Process 
{
    MyFunc
}

End 
{
    MyFunc
}

This code however does not execute. I get this error:

Begin : The term 'Begin' is not recognized as the name of a cmdlet, function, script file, or operable program.

Upvotes: 4

Views: 1981

Answers (2)

mklement0
mklement0

Reputation: 439183

The begin / process / end (and dynamic) blocks can only ever be used as the only top-level constructs:

  • in a script file (*.ps1)

  • in a function

In both cases, no other top-level code is allowed (apart from a param(...) parameter-declaration block at the top), a constraint that the placement of your script-internal MyFunc function violates.

If you want your script to use an internal helper function, place it inside the begin block - you'll be able to call it from the process / end blocks as needed:

Begin {
  function MyFunc {
    "hello"
  }
}

Process {
  MyFunc
}

End {
  MyFunc
}

The above yields:

hello
hello

That is, both the process and the end block successfully called the MyFunc function nested inside the begin block.

Generally, note that the begin / process / end blocks share the same local scope, which also applies to variables, so, similarly, you can initialize a script/function-local variable in the begin block and access it in the process block, for instance.
By the same token, nested functions - such as MyFunc here - are local to the enclosing script/function.

Upvotes: 6

Chase Florell
Chase Florell

Reputation: 47407

if you want to use begin/process/end in a script, you cannot have any other functions at the top level. Instead, you will define your internal functions within the begin block, and the remaining blocks will also have access to it.

begin 
{
    function MyFunc
    {
        Write-Host "Hello"
    }

    MyFunc
}

process {
    MyFunc
}

end {
    MyFunc
}

Upvotes: 1

Related Questions