skip to Main Content

I’m using PowerShell 5.1 and I’m using inline functions just fine in my script. But I can’t find anything online telling me why I wouldn’t use inline functions. My main context is using Azure pipeline tasks to call my PowerShell scripts.

enter image description here

2

Answers


  1. function-inline is a snippet for a function where the parameters are defined inline with the function name rather than in a parameter block.

    The function-inline creates:

    function FunctionName (OptionalParameters) {
        
    }
    

    Whereas a function is:

    function FunctionName {
        param (
            OptionalParameters
        )
        
    }
    

    The different location of OptionalParameters is the only difference.

    IMX, parameter blocks are typically preferred for all but the most trivial of functions.

    Login or Signup to reply.
  2. Bacon Bits helpful answer already shows the basic syntactic difference.

    A major difference is that you can’t use the CmdletBinding attribute with inline functions.

    Somewhat surprisingly, you can write advanced functions as both inline and non-inline functions:

    # Advanced function using inline syntax:
    function InlineFun( [Parameter()] $a ) { 
        $PSCmdlet 
    }
    
    # Advanced function using non-inline syntax:
    function Fun {
        param( [Parameter()] $a ) 
        $PSCmdlet 
    }
    

    A function becomes an advanced one if it either has CmdletBinding() or at least one Parameter() attribute. As proof the functions output the automatic $PSCmdlet variable, which is only available to advanced functions.

    One case where you actually need the param() block is when you want to write a parameter-less advanced function:

    function Fun {
        [CmdletBinding()] param() 
        $PSCmdlet 
    }
    

    In this case you need to use the CmdletBinding() attribute, which can’t be used with an inline function because it is an attribute of the param() block.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search