views:

89

answers:

3

Here is an example:

function ChildF()
{
  #Creating new function dynamically
  $DynFEx =
@"
  function DynF()
  {
    "Hello DynF"
  }
"@
  Invoke-Expression $DynFEx
  #Calling in ChildF scope Works
  DynF 
}
ChildF
#Calling in parent scope doesn't. It doesn't exist here
DynF

I was wondering whether you could define DynF in such a way that it is "visible" outside of ChildF.

+3  A: 

You can scope the function with the global keyword:

function global:DynF {...}

Shay Levy
In the given code above, `function global:DynF { ... }` probably makes more sense. ;-).
Bas Bossink
Thanks for the correction! I'll edit the thread.
Shay Levy
+2  A: 

Another option would be to use the Set-Item -Path function:global:ChildFunction -Value {...}

Using Set-Item, you can pass either a string or a script block to value for the function's definition.

Steven Murawski
+2  A: 

The other solutions are better answers to the specific question. That said, it's good to learn the most general way to create global variables:

# inner scope
Set-Variable -name DynFEx -value 'function DynF() {"Hello DynF"}' -scope global

# somewhere other scope
Invoke-Expression $dynfex
DynF

Read 'help about_Scopes' for tons more info.

Richard Berg