Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling functions from Process blocks

Tags:

powershell

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.

like image 487
dan-gph Avatar asked Oct 30 '25 00:10

dan-gph


1 Answers

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.

like image 122
mklement0 Avatar answered Nov 01 '25 19:11

mklement0



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!