🎓 A1Learner
🔍
0 of 52 lessons completed

PowerShell Writing Functions

A function is a named block of code that you can run again. You define it once, then you call it by its name whenever you need it.

Define a function and call it

The definition names the function and holds its code. Calling it by name runs that code.

function Get-Greeting {
    "Hello, friend"
}
Get-Greeting

Store what a function gives back

A function call can sit on the right side of an assignment. The variable then holds the value the function gave back.

function Get-Answer {
    42
}
$result = Get-Answer
$result

Call the same function twice

Reusing a function saves rewriting its code. Each call runs the whole code block again.

function Get-Welcome {
    "Welcome"
}
Get-Welcome
Get-Welcome

Example

function Get-Greeting {
    "Hello, friend"
}
function Get-Farewell {
    "Goodbye, friend"
}
Get-Greeting
$message = Get-Farewell
$message

Key points

  • Function: a named block of code that you can run again.
  • Define a function with the word function followed by its name and a code block.
  • Call a function by writing its name on its own line.
  • A function gives back whatever its code outputs.
  • Calling the same function twice runs its code twice.

In this example, two functions are defined, one for a greeting and one for a farewell. The greeting function is called directly. The farewell function is called inside an assignment, and the stored message is then printed.

Note

A function name uses a verb and a noun, just like a cmdlet name.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Which line defines a function named Get-Greeting?