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
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:
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
Advanced functions are functions that can perform operations that are similar to those performed by cmdlets. When a user wants to write a function without having to write a compiled cmdlet, they can use these functions.
The primary distinction between using a compiled cmdlet and an advanced function is that compiled cmdlets are.NET Framework classes that must be written in a.NET Framework language. Furthermore, the advanced functions are written in the PowerShell scripting language.
The following example shows how to use PowerShell’s advanced function:
function show-Message
{
[CmdletBinding()]
Param (
[ Parameter (Mandatory = $true)]
[string] $Name
)
Process
{
Write-Host ("Hi $Name !")
write-host $Name "today is $(Get-Date)"
}
}
show-message
Results:
cmdlet show-Message at command pipeline position 1
Supply values for the following parameters:
Name: Dhrub
Hi Dhrub !
Dhrub today is 09/01/2021 13:41:12
We use the function in every language and it usually brings down the number of lines a code has. If your code is 1000 lines then with the help of Function you can bring down the count to 500.Hope you have enjoyed this post, will see you in our next post.