Core Skills Level: Intermediate Chapter 8: Build Your Own Commands

Functions

A function is a named block of code. You define it once, then call it by name, with values passed in as parameters.

Lesson 1 of 2 in Chapter 8: Build Your Own Commands. Previous step in this path: Providers and drives. 3 learning objectives, 8 examples, and a knowledge check.

Start: what you will learn

A function is a named block of code. You define it once, then call it by name, with values passed in as parameters.

Learning objectives

  • Define a function with the function keyword
  • Add parameters with a param block
  • Call a function and use its output

Concept in simple words

What it is: A function is a small named block of code that you define once and then call by name, like a new command you made yourself. Once it is defined, you can use it just like a built in command, with its own name and its own inputs.

What problem it solves: Without functions, you copy and paste the same steps every time you need them. That gets long, it gets boring, and it gets risky, because when one copy needs a fix, the other copies still hold the old mistake. A function fixes that problem at the root. You keep one copy of the steps, in one place, and you call it whenever you need it.

Why it works

Why it works this way: When you call a function, PowerShell runs the code inside its block and sends the result back to the pipeline, which is the path that carries objects from one command to the next. Parameters, which are the named inputs a function accepts, let the same code work with different values each time, so you do not need a separate copy of the code for every case.

Think of it like this

Think of it like this: A function is like a recipe card in your kitchen. You write the steps once, and each time you cook, you just fill in the ingredients, which are your parameters, instead of writing the whole recipe again. If you improve the recipe, you change the one card, and every future meal gets the better version.

Here is a second picture that may help: A function is also like a small tool in a toolbox. You do not rebuild a hammer every time you need to hit a nail. You pick up the same hammer, you point it at a different nail, and the job gets done. The name is the handle you grab, and the parameters are the choices you make each time you use it.

Behind the command, part 1, define and call are two separate steps: Defining a function does not run its code. It only teaches PowerShell a new name and stores the steps behind that name. Calling the function is the step that actually runs the code. That is why a script that only defines a function can look like it did nothing. It did its job, it taught PowerShell the new command, but nobody asked it to run yet.

Behind the command, part 2, where the function lives: A function you define at the prompt lives in your current session. Close that session, and the function is gone, because it was never saved to a file. That is normal, and it is not an error. To keep a function, save it in a script file and load that file again when you need it, which you will learn more about in the reuse section below.

How it works, step by step

How it works, step by step, step 1, name it: First, you write the word function, then a clear name, then a block in braces, which are the curly brackets that group code together. Use the Verb-Noun shape for the name, such as Get-Greeting, where Get says what kind of action it is and Greeting says what it acts on. A clear name is a kindness to your future self, because you will read the name far more often than you will read the code inside.

How it works, step by step, step 2, list the inputs: Inside the block, you add a param section that lists each input, with a type in square brackets, such as [string] for text or [int] for a whole number, followed by a dollar sign and the input name. The word param is short for parameters. It is the guest list for your function. If a name is not on that list, the function does not expect it as a normal input.

How it works, step by step, step 3, write the work: Next, you write the work the function should do, using those input names inside the block. Every time you write $Name inside the block, PowerShell fills in the value that the caller gave for Name. The body should do one clear job. If it tries to do five jobs at once, it will be hard to read, hard to test, and hard to reuse.

How it works, step by step, step 4, call it by name: To use the function, you type its name and give a value for each parameter, for example Get-Greeting -Name "Izaz". PowerShell checks the types, runs the block, and returns the result, which you can show on screen, store in a variable, or send further down the pipeline. Defining and calling are both needed. Define first, then call.

How it works, step by step, step 5, use the result: The result of a function is not just text on the screen. It is output you can catch. You can store it with $greeting = Get-Greeting -Name "Izaz", and then use $greeting later. You can also pipe it onward, for example Get-Greeting -Name "Izaz" | Measure-Object, which counts what came through the pipeline. Think of the result as a parcel the function hands back to you, not as words it merely prints.

Types in depth: A type is a promise about the kind of value you expect. [string] means text, [int] means a whole number, [switch] means an on or off flag, and [string[]] means a list of text values. When you call the function, PowerShell tries to turn your value into the promised type. The text "4" can become the number 4, but the text "hello" cannot become a number, so PowerShell stops with an error before the body runs. That early stop is helpful. It tells you the input was wrong, instead of letting bad data quietly flow through your code.

Default values in depth: You can give a parameter a fallback value, such as param([string]$Name = "friend"). If the caller gives no value for Name, PowerShell uses "friend". If the caller gives a value, that value wins. A default value is useful for the most common case, but do not use it to hide a value that the caller really should choose each time. The caller should still be able to see, and change, the choice.

Named and positional calls: You can call a function with named values, such as Get-FullName -First "Izaz" -Last "Haider", or with values in order, such as Get-FullName "Izaz" "Haider". Both fill the parameters in the same way, because PowerShell matches position to the order in the param block. Named calls are clearer, especially when a function has many parameters, because the reader can see which value belongs to which input without counting. Use named calls in code you will share or read again later.

A function with no parameters: Not every function needs inputs. A function with no param block, such as function Get-Today { Get-Date }, simply runs the same steps each time. That is still useful, because it gives a repeated job a short, clear name. Add parameters only when the job genuinely changes from call to call.

Return in depth: In PowerShell, a function returns every value that is not captured, assigned, or sent somewhere else. You do not need the word return to send a value back. The last line "Hello, $Name" already sends the greeting out. The word return is still useful when you want to stop early, for example return "Too small" before the rest of the body runs. Remember that return only stops the function at that point. It does not erase values that were already sent out before it.

Keep the output clean: This return rule has one trap that catches many learners. If a line inside your function produces a value you did not mean to return, that value becomes part of the result. A short message meant only for the screen should go through Write-Host, which writes to the screen and not to the output pipeline, while a real result should be a plain value or Write-Output. If your function suddenly returns two things when you expected one, look for a stray line inside the body that produced extra output.

Collections in depth: If a function returns a list, PowerShell sends the items one at a time through the pipeline. That is why you can pipe the result into Measure-Object to count items, or into other commands that work item by item. If you store the result in a variable, you still get the whole collection back, just delivered one item at a time. This one at a time flow is the normal PowerShell way, and it is what makes functions fit so well into pipelines.

Scope in depth: A function gets its own child scope, which is a private workspace for that one call. Variables you create inside the function, and the parameters themselves, live in that workspace and do not leak out and overwrite variables outside. That protection is a gift. It means a function can use a helper name like $result without fear of breaking a $result you use elsewhere. Do not rely on reading a variable from outside the function, even if it sometimes works. Pass what the function needs through a parameter, so the function is honest about its inputs.

Let us walk through an example, Get-Greeting: In Get-Greeting, the param section says the function accepts one text input called Name. When you call Get-Greeting -Name "Izaz", PowerShell puts Izaz into $Name, then the line "Hello, $Name" builds the greeting. Look for the greeting text in the output, and if you see the literal text $Name instead, check that you used double quotes, because single quotes do not expand variables. If you change "Izaz" to "Sam", only the greeting changes, and nothing else in the function needs to change, which is exactly the power of a parameter.

Let us walk through an example, Add-Numbers: In Add-Numbers, the param block lists two whole number inputs, $A and $B. The body line $A + $B adds them and sends the sum out. The call Add-Numbers -A 3 -B 4 gives 7. If you change -B to 10, the result becomes 13, because the same addition runs with the new input. If you pass -A "hello", PowerShell cannot turn "hello" into a whole number, so it stops with a type error, which tells you the input was wrong before any addition happens.

Let us walk through an example, Get-FullName: function Get-FullName defines a new command. param lists two text inputs, $First and $Last, each typed as [string]. The line "$First $Last" joins them with a space and returns the result. The call Get-FullName -First "Izaz" -Last "Haider" fills in both inputs, so the same function would also work for any other first and last name. If you swap the values, the output order swaps too, because $First always comes before the space and $Last always comes after it.

Let us walk through an extra example, a default value: In the default value example, param([string]$Name = "friend") means Name is "friend" unless the caller says otherwise. The first call gives no value, so you see "Hello, friend". The second call gives -Name "Izaz", so you see "Hello, Izaz". Look at how one function covers both cases. If you change the default to "guest", only the no value call changes. The call that passes a name stays exactly the same.

Let us walk through an extra example, a switch: In the switch example, [switch]$Upper is not a value you fill in, it is a flag you either include or leave out. The call without -Upper returns the text as it is. The call with -Upper runs $Text.ToUpper(), which turns the text into capital letters. If you change the input text, both calls change their text, but only the -Upper call changes its case. A switch is the right tool when a choice is simply on or off, not a value to type in.

Let us walk through an extra example, capturing the result: In the capture example, Get-Double takes a number, doubles it, and sends the result out. The line $result = Get-Double -Number 6 catches that result in $result instead of letting it fall onto the screen and disappear. The next line, $result on its own, shows 12. If you change -Number to 10, $result becomes 20. This is the pattern you will use again and again: run the function, catch the result, then use it in the next step.

Let us walk through an extra example, scope in action: In the scope example, $Name is "Outside" before the function runs. Inside Get-InsideName, a new $Name is set to "Inside", and the function returns "Inside". After the call, $Name is still "Outside", because the inside change lived only in the function child scope. Look for that pair of lines in the output, "Inside" first, then "Outside". That pair is the proof that the function did not overwrite your outside variable.

Let us walk through an extra example, splatting: In the splatting example, $greetingArgs is a small table of parameter names and values, written with @{ Name = "Izaz" }. The call Get-Welcome @greetingArgs uses @ instead of $ in front of the variable name, and PowerShell unpacks the table into real parameters. The result is the same as Get-Welcome -Name "Izaz", but the table form is easier to read when a call has many parameters, and easier to build up step by step before the call.

Common mistakes and edge cases, the call shape: PowerShell functions do not use the call shape from many other languages. Do not write Get-FullName("Izaz", "Haider"). With that shape, PowerShell sees one grouped value, not two separate inputs, and the second parameter stays empty. Write Get-FullName -First "Izaz" -Last "Haider" instead, with spaces and parameter names. If a call gives a strange empty result, check for brackets and commas first, because that shape mistake is a very common cause.

Common mistakes and edge cases, empty and missing values: If a parameter has no default and the caller gives no value, it starts out empty, and the body may produce a strange greeting like "Hello, " with nothing after the comma. That is not a crash, it is a quiet wrong answer, which makes it harder to spot. Give a sensible default, or check the value inside the body, or move to the stricter checks in the next lesson, where you will learn how to require a value.

Common mistakes and edge cases, one job and one name: A function that does three unrelated jobs is hard to name, hard to test, and hard to reuse. If you cannot describe the function in one short sentence, split it into smaller functions and let one call the others. Also, avoid reusing a name that already belongs to a built in command, because your version will shadow it in that session and confuse anyone who expects the original behaviour.

When to use it

When to use it, and when not to: Use a function when you repeat the same steps more than once, when a script is getting long and hard to read, or when you want to share a handy task with someone else. Do not use a function for a one off command that you will never repeat, and do not hide a fixed value inside a function when a parameter would let it work for other cases too. A good test is simple: if you can imagine calling it a second time with different inputs, it deserves to be a function.

Reuse, dot sourcing in plain words: To reuse a function in a new session, save the definition in a script file, for example Tools.ps1, then load it into your current session with dot sourcing, which means typing a dot, a space, and the file path, such as . .Tools.ps1. After that load step, the function is available by name in that session. Running the file without the dot runs it in its own scope instead, so the function disappears when the file finishes, which is why so many learners think their saved function vanished. Dot sourcing is the load step, and calling is the run step, and both are needed.

Worked examples

Read each example in order. Each one explains its parts, then shows what to look for in the output.

Syntax

Syntax
function <Name> { param(<Type>$<Parameter>) <body> }

Example 1

Defines the function, then calls it with a value for -Name. The function returns the greeting text.

Example 1
function Get-Greeting {
  param([string]$Name)
  "Hello, $Name"
}
Get-Greeting -Name "Izaz"

Illustrative output: Hello, Izaz

Example 2

Two typed parameters. The function returns their sum, which you can store or pipe onward.

Example 2
function Add-Numbers {
  param([int]$A, [int]$B)
  $A + $B
}
Add-Numbers -A 3 -B 4

Illustrative output: 7

Example 3

function Get-FullName defines a new command. param lists two text inputs, $First and $Last, each typed as [string]. The line "$First $Last" joins them with a space and returns the result. The call Get-FullName -First "Izaz" -Last "Haider" fills in both inputs, so the same function would also work for any other first and last name.

Example 3
function Get-FullName {
  param([string]$First, [string]$Last)
  "$First $Last"
}
Get-FullName -First "Izaz" -Last "Haider"

Illustrative output: Izaz Haider

Example 4

The default value "friend" is used only when the caller gives no value for -Name. The first call shows "Hello, friend" and the second call shows "Hello, Izaz". Change the default to change only the no value case.

Example 4
function Get-Greeting {
  param([string]$Name = "friend")
  "Hello, $Name"
}
Get-Greeting
Get-Greeting -Name "Izaz"

Illustrative output: Hello, friend Hello, Izaz

Example 5

A switch is an on or off flag. Leave -Upper out for the text as it is. Add -Upper to turn the text into capital letters. No value follows -Upper itself.

Example 5
function Get-Shout {
  param([string]$Text, [switch]$Upper)
  if ($Upper) { $Text.ToUpper() } else { $Text }
}
Get-Shout -Text "hello"
Get-Shout -Text "hello" -Upper

Illustrative output: hello HELLO

Example 6

The assignment catches the function result in $result instead of letting it print and disappear. The last line shows $result, which is 12. Change -Number to 10 and $result becomes 20.

Example 6
function Get-Double {
  param([int]$Number)
  $Number * 2
}
$result = Get-Double -Number 6
$result

Illustrative output: 12

Example 7

The $Name inside the function lives in the function child scope. It returns "Inside", but the outside $Name stays "Outside" after the call. That pair of lines is the proof that the inside change did not leak out.

Example 7
$Name = "Outside"
function Get-InsideName {
  $Name = "Inside"
  $Name
}
Get-InsideName
$Name

Illustrative output: Inside Outside

Example 8

Splatting unpacks a table of parameters. The table uses @{ Name = "Izaz" }, and the call uses @greetingArgs, with @ instead of $. The result is the same as Get-Welcome -Name "Izaz", but the table form stays readable when a call has many parameters.

Example 8
function Get-Welcome {
  param([string]$Name)
  "Welcome, $Name"
}
$greetingArgs = @{ Name = "Izaz" }
Get-Welcome @greetingArgs

Illustrative output: Welcome, Izaz

Nothing on this page executes PowerShell code. The outputs above are illustrative only.

Common mistakes and troubleshooting

Read these before you try the examples, so you can spot the same problems in your own work.

  • Hard coding values inside a function instead of using parameters, so the function only works for one case.
  • Forgetting that a function defined in a script is only available after the script runs, and only in that session unless the script is dot sourced or in a module.
  • Calling a function before you have defined it in the same session, then thinking the function is broken, when PowerShell simply has not seen the definition yet, so define it first, then call it.
  • Calling a function with brackets and commas, such as Get-FullName("Izaz", "Haider"), which passes one grouped value instead of two separate inputs, so the second parameter stays empty.
  • Using single quotes around a value that should expand a variable, such as 'Hello, $Name', which prints the literal text $Name instead of the value.
  • Passing text that cannot convert to the parameter type, such as "hello" for an [int] parameter, which stops the call with a type error before the body runs.
  • Leaving a parameter empty with no default and no check, so the function quietly returns a half finished result such as "Hello, " instead of failing clearly.
  • Letting a stray line inside the body produce extra output, so the function returns more values than the caller expected, for example a helper command whose result was not captured or sent to Out-Null.
  • Reusing a name that already belongs to a built in command, so your function shadows the original in that session and surprises anyone who expects the original behaviour.
  • Writing one function that does several unrelated jobs, which makes it hard to name, hard to test, and hard to reuse, so split it into smaller functions that each do one clear job.

Knowledge check

Knowledge check

What does the param block do in a function?

Pick one answer. Feedback appears right away, and you can try again.

Remember this and next step

Remember this: A function gives a repeated task a name and a set of inputs, so you write it once, call it many times, and change it in only one place when it needs fixing. Define it first, pass values through named parameters, keep the output clean, and let the caller catch the result. That small discipline turns long, repeated scripts into short, clear tools that you can trust, share, and build on.

Next step: Advanced Functions