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
$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.