15

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?

2 Answers 2

15

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

Sign up to request clarification or add additional context in comments.

6 Comments

Can't recommend doing it this way highly enough. It is definitely the way that you want to go.
Thank you Jared. This is what I wanted. Dot sourcing reminded me of some other script languages I was working on earlier, and I thought it was cool. Now I realize that it was created for quick includes in the same path.
Do I understand this correctly, that modules have to be stored exactly at "<Path to the Documents folder>\WindowsPowerShell\Modules\<Module Folder>\<Module Files>" (per msdn.microsoft.com/en-us/library/dd878350(v=VS.85).aspx)? That's less than ideal for me (storing scripts in a repository, must be checked out to different location than above).
You can supply a path: Import-Module $ScriptRoot\modules\foo or you can alter $Env:PSModulePath to tell Powershell where to search for modules specified by bare name.
Maybe I have a unique use case but this method doesn't seem to work for me, I need to run Powershell scripts on remote servers but can't install anything on the server and I'm only allowed to do so with Invoke-Command remote session. This breaks as soon as I need to . include a script, my solution was to make a command line utility that takes in the intended source file and outputs the included scripts inline. This seems to work for allowing me to maintain my script in a sane way and use it with Invoke-Command -computername <servername>, do you see any obvious pitfalls with this?
|
10

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"

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.