I want to make my life easier when making scripts. I'm staring a little framework that will have a hierarchy of include files. The problem is dot sourcing a ps1 script that already has other files dot sourced brakes the scope in the original calling scripts. It looks like this:
$var = "shpc0001"
. '.\loadvariables.ps1'
. '.\config\config.ps1'
echo $var
The problem is that test.ps1
tries to load loadvariables.ps1
as it is located beside test.ps1
script.
How can I solve this?
The easiest way to manage a collection of scripts which have inter-dependencies is to convert them to modules. This feature is only available in 2.0 but it allows you to separate a group of scripts into independent components with declared dependencies.
Here is a link to a tutorial on getting modules up and running
As Jared said, modules are the way to go. But since you may even dot-source inside your modules, it is best to use full paths (which can still be calculated at run time) like so.
## Inside modules, you can refer to the module's location like so
. "$PSScriptRoot\loadvariables.ps1"
## Outside a module, you can do this
$ScriptRoot = Split-Path $MyInvocation.MyCommand.Path
. "$ScriptRoot\loadvariables.ps1"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With