简体   繁体   中英

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..

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.

In order to achieve what you want, you'll probably need to create a module. In the module, export the functions using Export-ModuleMember , and as long as you don't explicitly export any variables as module members, you should be fine.

Once you've created the module, import it using the Import-Module cmdlet.

My 2cents:

Usually (after a past Andy Arismendi answer! God bless you man!) I save all my scripts in $pwd folder (added in system path environment). The I can call them from the console wihtout dot sourcing and no script variable poisoning the console after a script ends his job.

If you cannot modify yours functions in simple scripts (sometimes it happens) I'm agree with Trevor answer to create a module and import it in $profile

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM