suppose have following code in module (called mymodule.psm1, in proper place module):
function new-function{ $greeting='hello world' new-item -path function:\ -name write-greeting -value {write-output $greeting} -options allscope write-greeting }
after importing module , running new-function can call write-greeting function (created new-function).
when try call write-greeting function outside scope of new-function call, fails because function not exist.
i've tried dot-sourcing new-function, doesn't help. i've supplied -option allscope
, apparently includes in child scopes.
i've tried explicitly following new-item call export-modulemember write-greeting doesn't give error, doesn't create function.
i want able create function dynamically (i.e. via new-item because contents , name of function vary based on input) function inside module , have newly created function available call outside of module.
specifically, want able this:
import-module mymodule new-function write-greeting
and see "hello world" output
any ideas?
making function visible pretty easy: change name of function in new-item have global:
scope modifier:
new-item -path function:\ -name global:write-greeting -value {write-output $greeting} #-options allscope
you're going have new problem example, though, because $greeting
exist in new-function
scope, won't exist when call write-greeting
. you're defining module unbound scriptblock, means $greeting
in scope (it's not going find it), in parent scopes. won't see 1 new-function
, way you'll output if module or global scope contain $greeting
variable.
i'm not sure real dynamic functions like, easiest way work around new issue create new closure around scriptblock this:
new-item -path function:\ -name global:write-greeting -value {write-output $greeting}.getnewclosure()
that create new dynamic module copy of state available @ time. of course, creates new problem in function won't go away if call remove-module mymodule
. without more information, i'm not sure if that's problem or not...
Comments
Post a Comment