Functions for selecting points from a file to the global area inside a function

I want to import an external function from a file, and not convert it to a module (we have hundreds of files for each function, so treating all of them as modules is too complicated).

Here is an explanation of the code. Please note that I have additional logic in the import function, for example, adding the root of the scripts folder and checking for the existence of the file and a special throw error to avoid duplication of code in every script that requires such an import.

C: \ Repository \ Foo.ps1:

Function Foo { Write-Host 'Hello world!' } 

C: \ InvocationTest.ps1:

 # Wrapper func Function Import-Function ($Name) { # Checks and exception throwing are omitted . "C:\Repository\$name.ps1" # Foo function can be invoked in this scope } # Wrapped import Import-Function -Name 'Foo' Foo # Exception: The term 'Foo' is not recognized # Direct import . "C:\Repository\Foo.ps1" Foo # 'Hello world!' 

Is there any trick to calculate the source in the global area?

+6
source share
3 answers

You cannot run the script in the parent scope, but you can create a function in the global scope by explicitly viewing it.

Something like this work for you?

 # Wrapper func Function Import-Function ($Path) { # Checks and exception throwing are omitted $script = Get-Content $Path $Script -replace '^function\s+((?!global[:]|local[:]|script[:]|private[:])[\w-]+)', 'function Global:$1' .([scriptblock]::Create($script)) } 

The above regular expression is intended only for root functions (left functions are justified, without a space to the left of the word function ). To target all functions, regardless of distance (including sub-functions), change the line $Script -replace to:

 $Script -replace '^\s*function\s+((?!global[:]|local[:]|script[:]|private[:])[\w-]+)','function Global:$1' 
+4
source

I canโ€™t remember a way to run a function in a global area. You can do something like this:

 $name = "myscript" $myimportcode= { # Checks and exception throwing are omitted . .\$name.ps1 # Foo function can be invoked in this scope } Invoke-Expression -Command $myimportcode.ToString() 

When you convert a script block to a .ToString() string, the variable will expand.

0
source

You can change the functions defined in files with an access point so that they are defined in the global scope:

 function Global:Get-SomeThing { # ... } 

When you place a source that is inside a function, the function defined in the dot file will be global. Not to say that this is the best idea, just another opportunity.

0
source

All Articles