Functions
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.
1. What is a Function?
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:
Get-ChildItem Function:\
Viewing Function Code
To view the code of a specific function:

Or:

2. Creating a Function
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:
3. Advanced Function Features
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:
4. Processing Piped Input
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:
5. Returning Results
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:
6. Error Handling
You can control how errors are handled using the -ErrorAction parameter.
Example:
Last updated
