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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With