开发者

Powershell: Include another script that has includes?

开发者 https://www.devze.com 2023-03-23 16:21 出处:网络
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

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?


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://learn.microsoft.com/en-us/powershell/scripting/developer/module/how-to-write-a-powershell-script-module


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"
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号