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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.