Functions in PowerShell (2021)
A step-by-step guide for function in PowerShell

In order to reuse the same code in multiple scripts, PowerShell functions are used.
PowerShell functions are a collection of PowerShell statements that have been given a name by the Whenever we want to run a function, we need to type its name.
Functions can have parameters, just like cmdlets. Pipeline or command-line access to function parameters is possible.
They return a value that can be assigned to variables or passed as a command-line argument or function parameter. In order to specify a return value, we can use the keyword return.
Function Syntax
Below is the syntax used for Function.
function [<scope:>]<name> [([type]$parameter1[,[type]$parameter2])]
{
param([type]$parameter1 [,[type]$parameter2])
dynamicparam {<statement list>}
begin {<statement list>}
process {<statement list>}
end {<statement list>}
}
The following terms are included in the syntax above:
- A function keyphrase
- A name that you have chosen
- Scope of Function (It is optional)
- There can be any number of named parameters.
- One or more PowerShell commands are enclosed in braces.
Example of a Function:
function Operation{
$num1 = 8
$num2 = 2
Write-Host "Multiply : $($num1*$num2)"
Write-Host "Addition : $($num1+$num2)"
Write-Host "Subtraction : $($num1-$num2)"
Write-Host "Divide : $($num1 / $num2)"
}
Operation
Results:
Multiply : 16
Addition : 10
Subtraction : 6
Divide : 4
Function Scope
- A function exists in the scope in which it was created in PowerShell.
- If a function is contained within a script, it is only available to the statements contained within that script.
- When we specify a function in the global scope, we can use it in other functions, scripts, and commands.
Click here to Read More →