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 what is up with text and no powershell?? Okey here we go.
How it works with code
Set-StrictMode -Version 3
Function Test-VirotFunction
{
param ([parameter(ValueFromPipeline)][string]$input)
Begin
{
Write-Host "Running Begin with `$input=$input"
}
Process
{
Write-Host "Running Process with `$input=$input"
}
End
{
Write-Host "Running End with `$input=$input"
}
}
'1','2','3' |Test-VirotFunction
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.
Function Test-VirotFunction
{
Begin
{
$i=0
Write-Host "Setting `$i in Begin to $($i)"
}
Process
{
$i++
Write-Host "Increasing `$i in Process to $($i)"
}
End
{
Write-Host "Last set value of `$i was $($i)"
}
}
'1','2','3' |Test-VirotFunction