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)

     


    © 2020 WinAdmin.org, All Rights Reserved.

    We use cookies on our website. Some of them are essential for the operation of the site, while others help us to improve this site and the user experience (tracking cookies). You can decide for yourself whether you want to allow cookies or not. Please note that if you reject them, you may not be able to use all the functionalities of the site.