Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell: Include another script that has includes?

Tags:

powershell

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:

\config\loadvariables.ps1

$var = "shpc0001"

\config\config.ps1

. '.\loadvariables.ps1'

\test.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?

like image 452
Vladimir Avatar asked Jul 29 '11 14:07

Vladimir


2 Answers

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

  • https://docs.microsoft.com/en-us/powershell/scripting/developer/module/how-to-write-a-powershell-script-module
like image 92
JaredPar Avatar answered Nov 08 '22 19:11

JaredPar


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"
like image 20
JasonMArcher Avatar answered Nov 08 '22 19:11

JasonMArcher