Is there any way for a powershell module to get at its caller's scope?

前端 未结 2 1434
鱼传尺愫
鱼传尺愫 2021-01-12 15:14

I have a collection of utility functions and other code that I dot-source into every powershell file I write. Having gotten bit by caller scope variables influencing it, I s

2条回答
  •  既然无缘
    2021-01-12 15:51

    $PSCmdlet.SessionState seems to provide a function inside a script module access to the call site's variables provided the call site is outside the module. (If the call site is inside the module, you can just use Get- and Set-Variable -Scope.) Here is an example using SessionState:

    New-Module {
        function Get-CallerVariable {
            param([Parameter(Position=1)][string]$Name)
            $PSCmdlet.SessionState.PSVariable.GetValue($Name)
        }
        function Set-CallerVariable {
            param(
                [Parameter(ValueFromPipeline)][string]$Value,
                [Parameter(Position=1)]$Name
            )
            process { $PSCmdlet.SessionState.PSVariable.Set($Name,$Value)}
        }
    } | Import-Module
    
    $l = 'original value'
    Get-CallerVariable l
    'new value' | Set-CallerVariable l
    $l
    

    which outputs

    original value
    new value
    

    I'm not sure whether SessionState was intended to be used in this manner. For what it's worth, this is the same technique used in Get-CallerPreference.ps1. There are also some test cases here which pass on PowerShell versions 2 through 5.1.

提交回复
热议问题