Every function has a beginning, a middle and an end.

Okey so I used a bit of artistic freedom there, the truth is that the main parts of a function is:

  • Parameters
  • Begin
  • Process
  • End

Parameters

So this is kinda self-explanatory. This is where we input all our parameters that the function will use. For today this is not really an important part so for simplicity I have created an input parameter called….(drumroll).. Input.

Begin

This script-block contains things that isn’t really dependent on any parameters that you supply. Here would be a good spot to verify that you have any required modules, have write access or connect to a database.

Process

This is the big script-block that has all the magic. All your core logic goes in here.

End

When you are done there might be things cleanup or close. Close any database connection that you opened in the beginning.

So whats up with text and no powershell?? Okey here we go.

How it works with code

So first lets just try a simple script that will just show that the Begin and End script-blocks will only be run once with no input parameter.

Powershell Function and inputvariable in Begin, PRocess and End scriptblocks

So is what we set in begin static for all future process script-blocks?

No it isn’t. I have used that to my advantage before. I also create a simple test function with a $i variable that is set in begin and increased in process until it reaches the end script-block.

Powershell Function variables carry over from Begin to Process to End

 

Leave a Reply