O'Reilly logo

Pro Windows PowerShell by Hristo Deshev

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required