Skip to content

Is there a way to invoke a scriptblock in its definition's scope and use param()? #6139

@alx9r

Description

@alx9r

Scriptblocks seem to be PowerShell's analog to other languages' anonymous functions. I'm finding scriptblock's role as anonymous anonymous functions critical to writing maintainable code. Unlike anonymous functions in C#, for example, how a scriptblock is invoked seems to affect its behavior. The method of invocation seems affect behavior in (at least) the following ways:

  1. Whether variable assignments in the scriptblock have side-effects in the definition's scope.
  2. Whether param() can be used.

Consider the following code:

New-Module m {
    $v = 'c'
    function f {
        param($sb)
        % $sb
    }
    function g {
        param($sb)
        & $sb -p1 'p1 is bound'
    }
} | Out-Null

'--- & ---'
& {
    $v = 'v is not modified by g'
    g -sb {
        param( $p1 )
        process
        {
            $p1
            $v = 'modified by g'
        }
    }
    $v
}

'--- % ---'
& {
    $v = 'v is not modified by f'
    f -sb {
        param( $p1 )  # <== these line are unused because % does not 
        $p1           # <== use parameter binding on this scriptblock
        $v = 'v is modified by f'
    }
    $v
}

which outputs

--- & ---
p1 is bound
v is not modified by g
--- % ---
v is modified by f

This seems to demonstrate the following:

  • assignments in scriptblocks invoked using & do not have side effects in the definition's scope
  • assignments in scriptblocks invoked using % do have side effects in the definition's scope
  • & supports param()

Judging from its help topic, % does not support using param().

The following table summarizes the behavior of % and & in these respects:

Invocation Method supports using param() variable assignment has side-effects
% no yes
& yes no

Is there a way to invoke scriptblocks that supports using both param() and variable assignments with side effects?

Metadata

Metadata

Assignees

No one assigned

    Labels

    Issue-Questionideally support can be provided via other mechanisms, but sometimes folks do open an issue to get aResolution-AnsweredThe question is answered.WG-Languageparser, language semantics

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions