Functions

Function is an important part of any programming language, like any other programming language PowerShell also allows developer to write a function. Function is simply a small part of the program itself. Whenever we have a very lenthy code then we can divide that code into smaller parts so it will be easy to read and easy to understand the code. We can also write the function for the code which we can resuse somewhere else too so it will reduce the line of code and easy to maintain.

Function is nothing but a collection of statements with a specific name according to it's functionality.

Function accepts argument(s) and returns value as well if we want to. Function can also access the variables of parent code block and function has it's own scope.

There are two types of functions in PowerShell, simple function and advanced function

Simple Function

In named function, function starts with function keyword, parameters between parenthesis and then name of the function and statements between two curly braces.

Example
function Addition($value1, $value2)
{
	return $value1 + $value2;
}

$val1 = 3;
$val2 = 4;

$sum = Addition $val1 $val2;

$sum;
// It will show output "The sum of value1 and value2 is :7"

In above function we have passed two parameters and returns sum of those two parameters.

Advanced Function

Advanced functions are very similar to inbuilt compiled Cmdlet commands. Main difference between Cmdlet commands and advanced function is, Cmdlet commands must be written into .NET Framework language and advance functions are again a set of PowerShell commands.

Example
function Greet-Person
{  
    [CmdletBinding()]  
    Param (  
        [ Parameter (Mandatory = $true)]  
        [string] $Name  
    )  
 
    Process
    {
        $currentHours = Get-Date -Format "HH";
        $greet = "Good Evening";

        if ($currentHours -ge 0 -and $currentHours -lt 12) {
            $greet = "Good Morning";
        }
        elseif ($currentHours -ge 12 -and $currentHours -lt 16){
            $greet = "Good Afternoon";
        }


        Write-Host ($greet + " " + $Name + "!")
    }
}

Greet-Person "Jack";

 

← Previous

Next →