PowerShell scripts and “Pattern Main”

Usually when I write PowerShell scripts I need to introduce a helper function

Script.ps1

for ($i = 0; $i -lt 10; $i++)
{
    Write-Host "$i * $i = $($i * $i)"
}

We want to extract a separate function

function Print-SquareEquality
{
    param
    (
        [int] $i
    )

    Write-Host "$i * $i = $($i * $i)"
}

for ($i = 0; $i -lt 10; $i++)
{
    Print-SquareEquality $i
}

As you we had to declare helper function before we can use it.
And when we introduce more and more functions we need to declare them before their usage.

I think this is very inconvenient. Your script file will eventually look like

function HelperFunction1
{
...
}

function HelperFunction2
{
...
}

...

function HelperFunction20
{
...
}

# Only here core script itself that uses all the functions

Usually when you read your script you are interested in your core script logic more than helper functions so it is more logical to have it at the top of the script

To have it, I invented a very simple pattern “Main”. You just need to wrap you core logic into a Main function at the beginning of the script and then call Main function at the end of the script.

function Main
{
    # Put our core script logic here
}

function HelperFunction1
{
...
}

function HelperFunction2
{
...
}

...

function HelperFunction20
{
...
}

Main

Now it is easier to read and still a valid script.

Pretty simple, isn’t it?

Advertisements

About mnaoumov

Senior .NET Developer in Readify
This entry was posted in Uncategorized and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s