Consider the following call site:
$modifiedLocal = 'original local value'
'input object' | SomeScriptblockInvoker {
$modifiedLocal = 'modified local value'
[pscustomobject] @{
Local = $local
DollarBar = $_
}
}
$modifiedLocal
I would like to implement SomeScriptblockInvoker such that
- it is defined in a module, and
- the scriptblock is invoked in the caller's context.
The output of the function at the call site would be the following:
Local DollarBar
----- ---------
local input object
modified local value
PowerShell seems to be capable of doing this. For example replacing SomeScriptblockInvoker with ForEach-Object yields exactly the desired output.
I have come close using the following definition:
New-Module m {
function SomeScriptblockInvoker {
param
(
[Parameter(Position = 1)]
[scriptblock]
$Scriptblock,
[Parameter(ValueFromPipeline)]
$InputObject
)
process
{
$InputObject | . $Scriptblock
}
}
} |
Import-Module
The output of the call site using that definition is the following:
Local DollarBar
----- ---------
local
modified local value
Note that DollarBar is empty when it should be input object.