PowerShell Functions

PowerShell Functions:

PowerShell Functions are extremely useful when working with PowerShell scripts that perform the same tasks repeatedly. You can make your functions as simple or as complex as necessary.

Syntax

The following is the syntax for a function:

function [] [([type]$parameter1[,[type]$parameter2])]
{
param([type]$parameter1 [,[type]$parameter2])
dynamicparam {<statement list>}
begin {<statement list>}
process {<statement list>}
end {<statement list>}
}

Simple Function

function hello { "Hello world!" }

hello

In the above PowerShell code, we are are defining a simple function named hello in first line and calling the function in next line. This function simply prints “Hello world!” to the console.

function testfunction {Get-Process}

testfunction

Syntax is as simple as function <function-name> {statements}

To use the function, type function-name.

function square($a)
{
    return $a*$a;
}

square(20);
square(19);

The above function will display square of any variable passed to the function.

Function Names

Functions names should consist of a verb-noun pair in which the verb identifies the action that the function performs and the noun identifies the item on which the cmdlet performs its action.

Functions with Parameters

You can use parameters with functions, including named parameters, positional parameters, switch parameters, and dynamic parameters.

Named parameters

Microsoft’s cmdlets mainly use named parameters.

Example:

function Restart-GivenService($service)
{
    Restart-Service $service
}

$s = "spooler"
Restart-GivenService($s)
Share on facebook
Share on twitter
Share on linkedin
Share on pinterest
Share on reddit
Share on skype
Share on telegram
Share on whatsapp
Share on email
Share on print

Leave a Reply

Your email address will not be published. Required fields are marked *

Post comment