Skip to content

Dot sourcing a function does not allow $MyInvocation to be used as a default parameter #4840

Closed

Description

It can be useful to run functions (vs. scripts) in the current scope. Joel Bennett (@Jaykul)'s Get-ParameterValues is an example

At the moment, it appears that a dot sourced function does not actually run in the current scope. Apologies if I'm using the wrong phrasing, the example should clarify things:

Steps to reproduce

function Test-MyInvocationParam {
    [cmdletbinding()]
    param($Invocation = $MyInvocation)
    $Invocation
}

function Test-Bug {
    [cmdletbinding()]
    param($a=1)
    . Test-MyInvocationParam
}

(Test-Bug).MyCommand.Name

Expected behavior

Test-Bug

Actual behavior

Test-MyInvocationParam

Environment data

> $PSVersionTable
Name                           Value
----                           -----
PSVersion                      6.0.0-beta
PSEdition                      Core
GitCommitId                    v6.0.0-beta.7
OS                             Darwin 16.7.0 Darwin Kernel Version 16.7.0: Th...
Platform                       Unix
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0

Activity

  1. lzybkr commented on Sep 14, 2017

    @lzybkr
    Contributor

    Dot sourcing is working exactly as designed.

    In your example, when you dot source Test-MyInvocationParam - no new scope is created, so the assignment $bug = $true happens in Test-Bug's scope.

    I think this is a better example to see what dot sourcing does:

    function Test-MyInvocationParam {
        $bug = $True
    }
    
    function Test-Bug {
        $bug = $False
        Test-MyInvocationParam
        Write-Host "Bug is present = $bug"
        . Test-MyInvocationParam
        Write-Host "Bug is present = $bug"
    }
    
    Test-Bug

    It should (and does) print:

    Bug is present = False
    Bug is present = True
    
  2. added
    Resolution-By Design
    on Sep 14, 2017
  3. changed the title [-]Dot sourcing a function does not appear to use the correct scope[/-] [+]Dot sourcing a function does not allow $MyInvocation to be used as a default parameter[/+] on Sep 15, 2017
  4. RamblingCookieMonster commented on Sep 15, 2017

    @RamblingCookieMonster
    Author

    Oy, my apologies, muddied the water by adding that illogical example and making assumptions about the cause - sorry!

    What I expect: param($Invocation = $MyInvocation) will receive MyInvocation from the calling function (Test-Bug), not the function being called (Test-MyInvocationParam)

    This behaves as expected in Windows PowerShell (Also works in 5.0, 4.0, 3.0, does not work in 2.0):

    $PSVersionTable
    
    Name                           Value                                               
    ----                           -----                                               
    PSVersion                      5.1.14393.1532                                      
    PSEdition                      Desktop                                             
    PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}                             
    BuildVersion                   10.0.14393.1532                                     
    CLRVersion                     4.0.30319.42000                                     
    WSManStackVersion              3.0                                                 
    PSRemotingProtocolVersion      2.3                                                 
    SerializationVersion           1.1.0.1   
    

    Cheers!

  5. lzybkr commented on Sep 15, 2017

    @lzybkr
    Contributor

    See this PR - if you still see the issue with that fix, reopen this issue.

  6. RamblingCookieMonster commented on Sep 18, 2017

    @RamblingCookieMonster
    Author

    Looks like that's rolled up in beta 7, which I've been running - yeah, still no luck - the underlying code is over my head, but initial thoughts:

    • Maybe due to the order of operations and this being in the param block?
    • Maybe due to dot sourcing a function in memory vs. a script?

    Either way - I can work around it for now, just need to explicitly pass the parameters I need. Not sure how to re-open an issue, I think that requires a certain level of access

    Cheers!

  7. added
    WG-Engine
    and removed
    Resolution-By Design
    on Sep 18, 2017
  8. daxian-dbw commented on Sep 19, 2017

    @daxian-dbw
    Member

    This is actually a bug that got fixed by PR #4709. There are 9 special automatic variables that are always available for every script run: $_, $args, $this, $input, $PSCmdlet, $PSBoundParameters, $MyInvocation, $PSScriptRoot and $PSCommandPath. When any of those variables are set, accessing the variables from within the script will get you those values.

    $args, $input, $PSBoundParameters are set to default values when it's not applicable; $MyInvocation is set to the script that's about to run; $PSScriptRoot and $PSCommandPath are set with the paths if the script is defined in a file, or an empty string if not; $_, $this may not be set depending on whether it's applicable; $PSCmdlet is set only for script cmdlets.

    The long-standing bug here is that when dot-sourcing script cmdlets (functions with [CmdletBinding()] or [Parameter()] attributes declared), those special variables are not properly set up before parameter binding -- they were set up after parameter binding. So using them for default parameter values will not get you the correct values, but using them in the script body will work as expected. For example, you can see the behavior by running the following in powershell prior to beta.7:

    function ScriptCmdlet {
        [CmdletBinding()]
        param($Invocation = $MyInvocation)
    
        "`$Invocation: $($Invocation.MyCommand.Name)"
        "`$MyInvocation: $($MyInvocation.MyCommand.Name)"
    }
    PS:49> . ScriptCmdlet
    $Invocation:
    $MyInvocation: ScriptCmdlet
    

    However, for simple functions (functions or scirpts that don't have [CmdletBinding()] or [Parameter()] attributes declared), those special variables have always been properly set up before parameter binding. See this example in any powershell versions:

    function SimpleFunction {
        param($Invocation = $MyInvocation)
    
        "`$Invocation: $($Invocation.MyCommand.Name)"
        "`$MyInvocation: $($MyInvocation.MyCommand.Name)"
    }
    PS:51> . SimpleFunction
    $Invocation: SimpleFunction
    $MyInvocation: SimpleFunction
    

    As you may already know, this inconsistent behavior has been there for years until the issue #4688 was reported. And then it was fixed by PR #4709.

  9. RamblingCookieMonster commented on Sep 19, 2017

    @RamblingCookieMonster
    Author

    Gotcha! So I think I see the issue. Might just be a design decision, or an old bug, but $MyInvocation used in a param block as a default value previously pointed to the command initiating the call - now it points to the command being called:

    function Test-MyInvocationParam {
        [cmdletbinding()]
        param($Invocation = $MyInvocation)
        $Invocation
    }
    
    function Test-Bug {
        [cmdletbinding()]
        param($a=1)
        . Test-MyInvocationParam
    }
    
    (Test-Bug).MyCommand.Name

    Output from different PowerShell versions:

    • PowerShell Core (with that PR, not sure about before): Test-MyInvocationParam
    • PowerShell 5.1: Test-Bug
    • PowerShell 5.0: Test-Bug
    • PowerShell 4.0: Test-Bug
    • PowerShell 3.0: Test-Bug
    • PowerShell 2.0: Test-MyInvocationParam

    Anyhow! I'll just explicitly include the parameter rather than relying on it as a default value

    Cheers!

  10. daxian-dbw commented on Sep 19, 2017

    @daxian-dbw
    Member

    but $MyInvocation used in a param block as a default value previously pointed to the command initiating the call - now it points to the command being called

    Yes, since $MyInvocation was not properly set before parameter binding when dot-sourcing a script cmdlet, the lookup will get the $MyInvocation from the scope of Test-Bug, and that's why you get the invocation instance for Test-Bug.

    If you make Test-MyInvocationParam a simple function by removing [cmdletbinding()], you will see the inconsistent behavior I mentioned before -- it prints out Test-MyInvocationParam on all versions of powershell.

    function Test-MyInvocationParam {
        param($Invocation = $MyInvocation)
        $Invocation
    }
    
    function Test-Bug {
        [cmdletbinding()]
        param($a=1)
        . Test-MyInvocationParam
    }
    
    PS:4> (Test-Bug).MyCommand.Name
    Test-MyInvocationParam
    
  11. added
    Resolution-By Design
    on Sep 19, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Resolution-By DesignWG-Engine

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions