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.


    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!" }

    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}

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

    To use the function, type function-name.

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

    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.


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

    $s = “spooler”


    © 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.