PowerShell:
Organizing code into functions

How to:

Let’s write a function to calculate the sum of two numbers. Simple, but it illustrates the point.

function Add-Numbers {
    param (
        [int]$FirstNum,
        [int]$SecondNum
    )
    return $FirstNum + $SecondNum
}

# Call the function with 5 and 10
$sum = Add-Numbers -FirstNum 5 -SecondNum 10
Write-Output "The sum is $sum"

Sample output:

The sum is 15

Deep Dive

Functions in PowerShell, like in most languages, are old news. We’ve been compartmentalizing code since the days of Fortran. It’s about ’not reinventing the wheel’. Alternatives? Sure, scripts or cmdlets. But they lack the tidiness and context-sensitivity of functions within scripts.

Implementation? Functions can be basic like our example or complex with scopes, pipeline input, and more. Take Advanced Functions. They mimic cmdlets with parameters that have attributes, like [Parameter(Mandatory=$true)]. That’s a taste of PowerShell’s flexibility.

See Also