Functions
Last updated
Last updated
Functions in PowerShell are reusable blocks of code that can accept parameters, return results, and even process piped input. They are essential for organizing and modularizing scripts, making them easier to read, maintain, and reuse.
A function is a named block of code stored in the function:\
drive. Functions can:
Accept parameters.
Return results.
Process piped input.
Be called from scripts or the interactive shell.
Listing Functions
To see all available functions in your session:
Viewing Function Code
To view the code of a specific function:
Or:
Basic Function
A function is defined using the function
keyword, followed by the function name and a script block ({}
).
Example:
Function with Parameters
Functions can accept parameters, which are variables passed into the function when it is called.
Example:
Function with Multiple Parameters
You can define multiple parameters and even assign default values.
Example:
Switch Parameters
Switch parameters are boolean parameters that don’t require a value. They are either present ($true
) or absent ($false
).
Example:
Default Parameter Values
You can assign default values to parameters, which are used if no value is provided.
Example:
Parameter Types
You can enforce specific data types for parameters.
Example:
Functions can process objects piped into them using the $input
variable or the Process
block.
Using $input
The $input
variable contains all piped objects.
Example:
Using the Process
Block
The Process
block processes each piped object individually.
Example:
Functions return the output of their last executed command. You can use the return
keyword to explicitly return a value and exit the function.
Example:
You can control how errors are handled using the -ErrorAction
parameter.
Example: