Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dot-sourcing functions from file to global scope inside of function

Tags:

powershell

I want to import external function from file, not converting it to a module (we have hundreds of file-per-function, so treat all them as modules is overkill).

Here is code explanation. Please notice that I have some additional logic in Import-Function like adding scripts root folder and to check file existence and throw special error, to avoid this code duplication in each script which requires that kind of 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 dot source to global scope?

like image 644
Anton Avatar asked Mar 03 '13 16:03

Anton


People also ask

What is Dot sourcing a function?

The dot sourcing feature lets you run a script in the current scope instead of in the script scope.

Are variables scoped in PowerShell?

PowerShell ScopesThe variables, aliases, and functions in your PowerShell profiles are also created in the global scope. The global scope is the root parent scope in a session. Local: The current scope.

What is scope script?

The Script scope is shared across all children in a script or script module. The Script scope is a useful place to store variables which must be shared without exposing the variable to the Global scope (and therefore to anyone with access to the session).


2 Answers

Just dot-source the function as well:

. Import-Function -Name 'Foo'
Foo # Hello world!
like image 145
stijn Avatar answered Oct 23 '22 03:10

stijn


You can change the functions that are defined in the dot-sourced files so that they are defined in the global scope:

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

When you dot source that from within a function, the function defined in the dot sourced file will be global. Not saying this is best idea, just another possibility.

like image 20
briantist Avatar answered Oct 23 '22 05:10

briantist