Functions in PowerShell (2021)

Dhrub Bharali
2 min readNov 11, 2021

A step-by-step guide for function in PowerShell

Functions 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:

  1. A function keyphrase
  2. A name that you have chosen
  3. Scope of Function (It is optional)
  4. There can be any number of named parameters.
  5. 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 →

--

--

Dhrub Bharali
0 Followers

Full time Powershell script writer and half time gamer!!