Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Putting functions in separate script and dot-sourcing them - what will the scope be

I've put my functions in a separate file and I call the file with:

$workingdir = Split-Path $MyInvocation.MyCommand.Path -Parent
. "$workingdir\serverscan-functions.ps1"                        

But, if I call the scripts like

my-function

how will the variable scope (from within "my-function") be? Should I still $script:variable to make the variable exist outside the function or have I dot-sourced the function as well?

Hope I don't confuse anyone with my question... I've tried to make it as understandable as possible, but still learning all the basic concept so I find it hard to explain..

like image 696
Sune Avatar asked Feb 21 '12 19:02

Sune


1 Answers

When you dot source code it will behave as if that code was still in the original script. The scopes will be the same as if it was all in one file.

C:\functions.ps1 code:

$myVariable = "Test"

function Test-DotSource {
    $script:thisIsAvailableInFunctions = "foo"
    $thisIsAvailableOnlyInThisFunction = "bar"
}

main.ps1 code

$script:thisIsAvailableInFunctions = ""

. C:\functions.ps1

# Call the function to set values.
Test-DotSource

$script:thisIsAvailableInFunctions -eq "foo" 
# Outputs True because of the script: scope modifier

$thisIsAvailableOnlyInThisFunction -eq "bar" 
# Outputs False because it's undefined in this scope.

$myVariable -eq "Test"                       
# Outputs true because it's in the same scope due to dot sourcing.
like image 161
Andy Arismendi Avatar answered Oct 10 '22 17:10

Andy Arismendi