5.1. Defining Functions

A function is very similar to a script block in the sense that it contains executable code. The main difference between the two is that a script block is anonymous—it has to be assigned to a variable before it can be evaluated. Functions get their names at the time of their creation, and that name makes them immediately available for execution. To define a function, we have to use the function keyword in the following form:

function <name>(<parameter list>)
{
    <function body>
}

The function name should start with a letter and can contain any alphanumeric character sequence, as well as hyphens and underscore characters. This is how we can define a simple function that outputs some text:

PS> function Say-Hi() { Write-Host ...

Get Pro Windows PowerShell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.