Run In Module
December 10th, 2010 by KarlHave you even been working on a a module, call a function, but then get frustrated because you can’t get to that $script:something.
Well modules and scopes is an interesting problem. and when you something from the command prompt of a function OUTSIDE of the module, you can’t see things. This can make working and debugging on things (outside of breakpoints etc) difficult.
Well thankfully there is an undocumented feature on the & call operator
so instead of
& { … }
you can pass in a reference to a module and run a scriptblock
& (get-module somemodule) { … }
and the scriptblock will be run in the modules context..
Well that can be tedious so i’ve made a function called invoke-scriptblockinmodule , with the alias RIM
that allows you to do
rim somemodule { … }
and after you have specified the modulename once, it remembers it so you can just do
rim { … }
Enjoy,
function invoke-scriptblockinmodule
{
[CmdletBinding(DefaultParameterSetName="noname")]
param (
[Parameter(ParameterSetName='noname', Position=1, mandatory = $true)]
[Parameter(ParameterSetName='hasname', Position=2,mandatory = $true)]
[scriptblock]$scriptblock ,
[Parameter(ParameterSetName='hasname', Position=1)]
[string] $modulename = $null
)
#TODO: do get-module first and make sure its valid before invoking with &
if (!$global:prossertools) { $global:prossertools = @{} }
if ($modulename) {
$global:prossertools.invokescriptblockinmodulecachedname = $modulename;
$module = get-Module ($global:prossertools.invokescriptblockinmodulecachedname)
& $module $scriptblock;
}
else {
if (!$global:prossertools.invokescriptblockinmodulecachedname ) {
write-host "no name provided or currently cached"
}
else {
$module = get-Module ($global:prossertools.invokescriptblockinmodulecachedname)
& $module $scriptblock;
}
}
}
set-Alias rim invoke-scriptblockinmodule
Posted in Powershell | No Comments »
