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)

     


    © 2019 WinAdmin.org . All Rights Reserved.
    Cookies make it easier for us to provide you with our services. With the usage of our services you permit us to use cookies.
    Ok Decline