Skip to content

Is there a supported way of binding an unbound scriptblock to the "global" SessionState? #6147

Closed

Description

@alx9r

I have been experimenting with a (hopefully) more robust mechanism for mocking commands than Pester currently uses. Here is a proof of concept. In general, the mechanism relies on invoking scriptblocks with the SessionState where the mock needs to exist. This is trivial for a SessionState associated with a module: Invoking & $module $scriptblock achieves the desired result. I haven't, however, found a straightforward way of invoking a scriptblock defined inside a module with the "global" SessionState.

Consider this working code

Get-Module LibraryModule,m | Remove-Module
New-Module LibraryModule {
    $sb = {
        Write-Host 'control flow: 1'
        Write-Host $v
        'output'
        Write-Host 'control flow: 3'
    }
    function DownStream {
        param([Parameter(ValueFromPipeline)]$i)
        process {
            Write-Host 'control flow: 2'
        }
    }
    function InvokeWithModuleSessionState {
        param([psmoduleinfo]$mi)
        & $mi $sb | DownStream
    }
    function InvokeWithGlobalSessionState {
        [CmdletBinding()]
        param($ss)

        <#
        This doesn't execute in the "global" SessionState.  
        (ie. it has no access to 'g.v')
        #>
        # & $ss.InvokeCommand.NewScriptBlock($sb) | DownStream

        <#
        Each of these neither
            1. has the correct control flow (ie. they don't yield to DownStream), nor
            2. executes in the global SessionState (ie. they have no access to 'g.v').
        #>

        # $ss.InvokeCommand.InvokeScript($sb) | DownStream
        # $ss.InvokeCommand.InvokeScript($ss,$sb,$null) | DownStream
        # $ss.InvokeCommand.InvokeScript($true,$sb,$null,$null) | DownStream
        # $ss.InvokeCommand.InvokeScript($false,$sb,$null,$null) | DownStream
        # $ss.InvokeCommand.InvokeScript($sb,$true,'Output',$null,$null) | DownStream
        # $ss.InvokeCommand.InvokeScript($sb,$false,'Output',$null,$null) | DownStream

        <#
        This works, but it's in bucket 4.
        #>

        $copyOfSb = [scriptblock]::Create($sb)
        $flags = [System.Reflection.BindingFlags]'Instance,NonPublic'
        $internalSessionState = [System.Management.Automation.SessionState].GetProperty('Internal', $flags).GetValue($ss, $null)
        $property = [ScriptBlock].GetProperty('SessionStateInternal', $flags)
        $property.SetValue($copyOfSb, $internalSessionState, $null) | Out-Null
        & $copyOfSb | DownStream
    }
} | Import-Module

New-Module m {
    $v = 'm.v'
} | Import-Module

& {
    $v = 'g.v'
    Write-Host '=== Module ==='
    InvokeWithModuleSessionState -sb $sb -mi (Get-Module m)

    Write-Host '=== Global ==='
    InvokeWithGlobalSessionState -ss $ExecutionContext.SessionState
}

which outputs

=== Module ===
control flow: 1
m.v
control flow: 2
control flow: 3
=== Global ===
control flow: 1
g.v
control flow: 2
control flow: 3

This implementation of InvokeWithGlobalSessionState relies on private reflection to bind a scriptblock to the SessionState. This is clearly vulnerable to bucket 4 changes which, per the breaking changes contract, "don't require up-front approval." I'd like to avoid such sudden breakage, if there is a better way.

  1. Is there a supported way of binding an unbound scriptblock to the "global" session state?
  2. Is there a supported way of invoking an unbound scriptblock in the "global" session state? In other words, is there a supported analog to & $module $scriptblock that works for the "global" session state as opposed to a module session state?
  3. Is there some other way of creating a scriptblock from a module, but invoking it in the "global" session state?

Activity

  1. lzybkr commented on Feb 12, 2018

    @lzybkr
    Contributor

    I believe you'll have to rely on a conversion to string, but something like the following might work:

    function global:BindToGlobalSessionState([scriptblock]$sb)
    {
        Invoke-Expression "{`n$sb`n}"
    }

    The idea is to recreate the script block in global scope.

    Basically, you want to get this line of code executed with the correct session state.

    There are other places where SessionState is assigned, but this is typically the first, and once set, the session state can't change.

  2. changed the title [-]Is there a supported way to binding an unbound scriptblock to the "global" SessionState?[/-] [+]Is there a supported way of binding an unbound scriptblock to the "global" SessionState?[/+] on Feb 12, 2018
  3. SeeminglyScience commented on Feb 12, 2018

    @SeeminglyScience
    Contributor

    If you already have the session state, you can create a dummy module to store it. The SessionState property is writable (mistake, maybe?)

    function InvokeWithSessionState {
        param($SessionState, $ScriptBlock)
        end {
            $module = [psmoduleinfo]::new(<# linkToGlobal: #> $false)
            $module.SessionState = $SessionState
            & $module $ScriptBlock
        }
    }

    That said, I assume the actual implementation of this will be running within Pester's SessionState. If that's the case, actually obtaining the global SessionState is the harder part. I haven't been able to find a way to get that without reflection.

  4. alx9r commented on Feb 13, 2018

    @alx9r
    Author

    I believe you'll have to rely on a conversion to string...The idea is to recreate the script block in global scope.

    I see. It's not obvious to me how to do that from a module.

    New-Module m {
        function global:GetGlobalSessionState { $ExecutionContext.SessionState }
    } | Import-Module
    
    [object]::ReferenceEquals((f),$ExecutionContext.SessionState)

    outputs False.

    In other words, despite the global: prefix, GetGlobalSessionState's scriptblock is bound to the module.

    Is there some other way to reliably get a reference to a scriptblock associated with the global session state?

    If you already have the session state, you can create a dummy module to store it.

    This seems promising, and $PSCmdlet.SessionState seems to contain the caller's session state. The following code seems to prove the concept:

    New-Module m {
        New-Module n {
            $v = 'n.v'
            $sb = {$v}
            function InvokeWithSessionState {
                param($SessionState, $ScriptBlock)
                $module = [psmoduleinfo]::new(<# linkToGlobal: #> $false)
                $module.SessionState = $SessionState
                & $module $ScriptBlock
            }
            function a {
                [CmdletBinding()]param()
                InvokeWithSessionState -SessionState $PSCmdlet.SessionState -ScriptBlock $sb
            }
            function b {a}
        } | Import-Module
    
        $v = 'm.v'
        function c { a }
    } | Import-Module
    
    & {
        $v = 'g.v'
        a
        b
        c
    }

    That outputs

    g.v
    n.v
    m.v
    

    It seems like this technique would not be vulnerable to any of the acceptable breaking changes in the breaking changes contract. Jason Shirk (@lzybkr) Can you comment on whether this behavior is likely to be broken in the future?

  5. SeeminglyScience commented on Feb 13, 2018

    @SeeminglyScience
    Contributor

    alx9r $PSCmdlet won't reliably get you the global session state because you can't tell what scope it's coming from. You can't really even be sure that it'll actually be there, if the module is called from a command prompt or a script without CmdletBinding that won't work.

    You could get a little closer by iterating the call stack, something like

    (Get-PSCallStack).GetFrameVariables().PSCmdlet.Value |
        Where-Object { -not $_.SessionState.Module }

    But that still depends on some part of the call stack outside of a module declaring CmdletBinding

  6. lzybkr commented on Feb 13, 2018

    @lzybkr
    Contributor

    alx9r - I can see why that example doesn't work using new-module, but it should work if you defined the function in module when you use the ScriptsToProcess entry in the module manifest.

    I agree with Patrick Meinecke (@SeeminglyScience) that a writable SessionState property in ModuleInfo seems unintentional. Changes to apis are generally conservative, so maybe you'd be safe using it, but I'd continue looking for alternatives so you have options to consider, or even fall back on if the api was removed.

  7. alx9r commented on Feb 13, 2018

    @alx9r
    Author

    $PSCmdlet won't reliably get you the global session state because you can't tell what scope it's coming from.

    I agree. I've been experimenting with different approaches since my OP and I think the question I should have been asking is this: Is there a supported way of invoking a scriptblock with the caller's SessionState? It seems like $PSCmdlet.SessionState reliably gets the caller's SessionState.

  8. alx9r commented on Feb 13, 2018

    @alx9r
    Author

    it should work if you defined the function in module when you use the ScriptsToProcess entry in the module manifest.

    I thought so too. And it does work, but that approach is brittle to nested modules. If any module loads the module with ScriptToProcess first, then BindToGlobalSessionState actually binds to that module's SessionState.

    Changes to apis are generally conservative, so maybe you'd be safe using it, but I'd continue looking for alternatives so you have options to consider, or even fall back on if the api was removed.

    I think I'm out of ideas for now. Do you have any other ideas I should explore? FWIW, I think the question I probably should have been asking is this: Is there a supported way of invoking a scriptblock with the caller's SessionState?

  9. SeeminglyScience commented on Feb 13, 2018

    @SeeminglyScience
    Contributor

    It seems like $PSCmdlet.SessionState reliably gets the caller's SessionState.

    alx9r not reliably, because you can't guarantee CmdletBinding was declared in the caller. You could make that a requirement to mock, but if it wasn't declared and instead PSCmdlet came from a different SessionState than the caller it would be very difficult to debug unless you are intimately familiar with the engine.

    Your best bet at reliability (not taking support into account) is to get InvocationInfo from the call stack and get the SessionStateInternal of the caller.

    $callerScriptBlock = (Get-PSCallStack)[1].InvocationInfo.MyCommand.ScriptBlock
    
    $ssi = $callerScriptBlock.GetType().
        GetProperty('SessionStateInternal', [System.Reflection.BindingFlags]'Instance, NonPublic').
        GetValue($callerScriptBlock)

    But even then there are some instances where the ScriptBlock property is null (like class methods and script blocks invoked directly with Invoke* api's)

  10. added
    WG-Language
    Issue-Discussion
    on Feb 13, 2018
  11. alx9r commented on Feb 13, 2018

    @alx9r
    Author

    FWIW I have settled on implementing a function called BindToCallerSessionState, for now. The function does the following:

    • Attempts each of the following strategies and uses the one highest in the list that succeeds:
      1. setting the session state property of a new [psmoduleinfo]
      2. setting a scriptblock's SessionStateInternal property using private reflection
      3. calling BindToImporterSessionState which is implemented using ScriptToProcess
    • Writes to the warning stream if any strategy fails.
    • Throws and exception if they all fail.

    The problem with strategies (i) and (ii) is that they might be broken by changes to PowerShell. The problem with (iii) is that it doesn't do the right thing -- binding to the importer session state is not the same as binding to the caller session state. This seems to be a matter of choosing the least evil.

    I have also implemented a number of automated tests around each of the strategies. If there is a breaking change, it should be detected early either by the warnings seen by users or by the automated tests for the mock library failing.

    It does seem a bit odd that PowerShell has a first class way of invoking a scriptblock in a given module (ie. & $module $scriptblock) but no supported way of invoking a scriptblock in either the "global" session state or the caller's session state.

  12. alx9r commented on Feb 13, 2018

    @alx9r
    Author

    not reliably, because you can't guarantee CmdletBinding was declared in the caller.

    This code

    New-Module m {
        $v = 'm.v'
        function s { {$v} }
        function InvokeWithCallerSessionState {
            [CmdletBinding()]
            param($ScriptBlock)
            $module = [psmoduleinfo]::new(<# linkToGlobal: #> $false)
            $module.SessionState = $PSCmdlet.SessionState
            & $module $ScriptBlock
        }
    } | Import-Module
    
    $v = 'g.v'
    $sb = s
    
    & $sb # m.v
    InvokeWithCallerSessionState -ScriptBlock $sb # g.v

    seems to demonstrate that declaring CmdletBinding in the caller is not necessary. Do you have an example demonstrating your concern?

  13. SeeminglyScience commented on Feb 13, 2018

    @SeeminglyScience
    Contributor

    Do you have an example demonstrating your concern?

    Nope! I'm wrong. I could have sworn $PSCmdlet.SessionState gave the current session state, but that isn't the case. Learn something new every day :)

  14. alx9r commented on Jun 18, 2019

    @alx9r
    Author

    I think there is another alternative. As far as I can tell, when a PSCmdlet implemented in C# is invoked its SessionState property is the caller's SessionState. In other words,

    • when such a cmdlet is invoked from outside a module, .SessionState is the "global" SessionState, and
    • when such a cmdlet is invoked from a script module, .SessionState is the module's SessionState.

    Jason Shirk (@lzybkr) Can you confirm whether this is true? I'm also wondering whether this behavior is by design or by chance. In other words, can I rely on the correspondence between call site and .SessionState as described in the above bullets?

    Below is (what I think is) a working example. It looks like utilizing this technique requires that any command to whose call site you need to bind a scriptblock be implemented as a binary command. I haven't succeeded at replicating this technique for implementing commands as scriptblocks.

    Add-Type '
        using System.Management.Automation;
    
        [Cmdlet(VerbsData.ConvertTo,"CallerBound")]
        public class ConvertToCallerBound : PSCmdlet
        {
            [Parameter(Mandatory=true)]
            public ScriptBlock ScriptBlock;
    
            protected override void ProcessRecord()
            {
                WriteObject(
                    SessionState.InvokeCommand.InvokeScript(
                        "{$v}"
                    )[0]);
            }
        }
    ' -PassThru | % Assembly | Import-Module
    
    $null = New-Module {
        $v = 'm.v'
        function ConvertTo-ModuleBound
        {
            param(
                [Parameter(Mandatory)]
                $ScriptBlock
            )
            <#
            .SessionState in this call to ConvertTo-CallerBound
            is this module's SessionState.
            #>
            ConvertTo-CallerBound -ScriptBlock $ScriptBlock
        }
        function Invoke-ScriptBlock{
            param($ScriptBlock)
            & $ScriptBlock
        }
    }
    
    $v = 'g.v'
    
    <#
    Returns a new scriptblock that is
    bound the "global" scope.
    
    .SessionState in this call to ConverTo-CallerBound
    is the "global" scope.
    #>
    $g = ConvertTo-CallerBound -ScriptBlock {$v}
    
    & $g # g.v
    Invoke-ScriptBlock $g # g.v
    
    
    <#
    Returns a new scriptblock that is 
    bound to the module's scope.
    #>
    $m = ConvertTo-ModuleBound -ScriptBlock {$v}
    & $m # m.v
    Invoke-ScriptBlock $m # m.v
  15. vexx32 commented on Jun 18, 2019

    @vexx32
    Collaborator

    Heh, can't believe I never found this issue.

    I've wrestled with this extensively myself in PSKoans, so that I could invoke the koan files in a global session rather than accidentally invoking them inside the module itself.

    My own solution was basically to spin up a new runspace and work with that.

    If there is a simpler way to bind a scriptblock to the global session state I'd very much appreciate it.

  16. lzybkr commented on Jun 18, 2019

    @lzybkr
    Contributor

    I'm not going to answer your question directly because it's been a long time since I've looked at this area and your observations are going to be more correct than my possibly faulty memory.

    IIRC, SessionState can be set upon first access (or explicitly) and I didn't like that as it wasn't explicit enough for my liking.

    Because of this, I think it's possible it gets set by chance somewhere now, but I think Bruce Payette (@BrucePay) was careful enough when originally implementing modules that everything is (or at least once was) by design.

  17. alx9r commented on Jun 18, 2019

    @alx9r
    Author

    Jason Shirk (@lzybkr) Ah. I see. Got it. Thanks for the background. I think I've got enough tests around the behavior I need that I'll probably detect an inadvertent change early enough.

  18. alx9r commented on Jun 18, 2019

    @alx9r
    Author

    If there is a simpler way to bind a scriptblock to the global session state I'd very much appreciate it.

    Rain Sallow (/u/ta11ow) (@vexx32) The best I've been able to come up with is the methods for binding to the caller's session state (which may or may not be the global session state) discussed above. Binding to the global session state is a bridge further than I have explored.

  19. microsoft-github-policy-service commented on Nov 16, 2023

    @microsoft-github-policy-service
    Contributor

    This issue has not had any activity in 6 months, if this is a bug please try to reproduce on the latest version of PowerShell and reopen a new issue and reference this issue if this is still a blocker for you.

  20. microsoft-github-policy-service commented on Nov 16, 2023

    @microsoft-github-policy-service
    Contributor

    This issue has not had any activity in 6 months, if this is a bug please try to reproduce on the latest version of PowerShell and reopen a new issue and reference this issue if this is still a blocker for you.

  21. added
    Resolution-No Activity
    on Nov 16, 2023
  22. microsoft-github-policy-service commented on Nov 16, 2023

    @microsoft-github-policy-service
    Contributor

    This issue has not had any activity in 6 months, if this is a bug please try to reproduce on the latest version of PowerShell and reopen a new issue and reference this issue if this is still a blocker for you.

  23. microsoft-github-policy-service commented on Nov 23, 2023

    @microsoft-github-policy-service
    Contributor

    This issue has been marked as "No Activity" as there has been no activity for 6 months. It has been closed for housekeeping purposes.

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

    Issue-DiscussionResolution-No ActivityWG-Language

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions