Begin-Process-End in a PowerShell script

Much has been written about how you need to use Begin/Process/End blocks in order to handle a collection of values passed from the pipeline, but those posts all seem to focus on how to do it in a *function*, not a script.

I recently struggled to figure out how to retrofit this functionality into one of my existing PowerShell scripts.

If you’re here I guess you already know WHY you want to do it, but it’s the HOW what’s causing you distress.

Seen this and had your script dump a list of running processes to screen?

begin : The term 'begin' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling
of the name, or if a path was included, verify that the path is correct and try again.

The trick is simple: there can be NO executable code outside the B/P/E blocks. Nothing. No ‘statics’, no hash tables declared, no functions, not a sausage. Once you move the lot into the Begin block, it’s plain sailing.

Here’s a working example. If you save this to a file and run it with say “gci *.ps1 | test-BeginProcessEnd.ps1” it will dump the names of the scripts in that directory to screen, one after the other, along with some other text showing when the Begin and End blocks fire.

<#  
.SYNOPSIS  
	A demo of Begin-Process-End in a SCRIPT.

.DESCRIPTION  
	A demo of Begin-Process-End in a SCRIPT.
#>

[CmdletBinding()]
param(
	[parameter(ValueFromPipelineByPropertyName = $true)] 	
	[alias('f','FullName')][string[]]$Filename
)

begin
{

	$scriptVersion = "1"
	$Error.Clear()	  #Clear PowerShell's error variable
	$Global:Debug = $psboundparameters.debug.ispresent

	function testing-something
	{
		write-host "Stuff happens here"
	}
	
	function more-something
	{
		write-host "More stuff happens here"
	}
	
	write-host "Begin - only executes once"
}

process
{
	write-host "Process - runs for every member of the collection that was passed"
	write-host $_.FullName
}

end
{
	write-host "End - only executes once, when we're done"
}

It looks really simple once you know how, I know. Hopefully someone else will benefit from this little gem.

Revision History

18th February 2020. This is the initial publication.


 

– G.

One Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

... and please just confirm for me that you're not a bot first: Time limit is exhausted. Please reload the CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.