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

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


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