tags:

views:

46

answers:

2

I have a main script that is calling on several others scripts and I need to load the variables from the other scripts into the main script so that I can dump them into a html file. I tried dot sourcing the scripts I am calling on but that did not work or I am doing something wrong. Any help would be appreciated.

Example section of script:

.\get-cluster.ps1

$MyReport += Get-CustomHeader "Clusters not in compliance : $($CapacityInfo.count) ($MyReport += Get-HTMLTable $capacityinfo
$MyReport += Get-CustomHeaderClose

The variable $capacityinfo exists in the get-cluster.ps1 script

+2  A: 

Unless your get-cluster.ps1 file is in your root dir, dot source would look more like this:

. .\Get-Cluster.ps1

This will execute the Get-Cluster.ps1 script in the same scope as the caller making its script level variables available in the caller.

Keith Hill
Thanks for the reply. My script was not in the root dir so I was not calling it probably. Thanks for the help.
jrob24
+2  A: 

Dot sourcing will accomplish your goal. However, this is an ambiguous design and conflicts with the PowerShell CmdLet Development Guidelines. Granted you are authoring a script and not a Cmdlet but it appears you're trying to follow PowerShell conventions given the script file name you have chosen.

Using the verb Get implies that you are retrieving a resource. So if you have a script called Get-Cluster.ps1 then it should retrieve one or more Cluster instances. Consider the following instead:

$clusters = .\Get-Cluster.ps1 -NonCompliantOnly

This will still enable you to set a variable in your current scope without all the magic and ambiguity of dot sourcing. I'm not trying to be preachy but the PowerShell team has done a good job creating creating consistency and I think there is a lot of value in attempting to perpetuate that when we extend PowerShell with our own scripts/modules/cmdlets. If you're dead set on setting a new or existing variable in the current scope using dot sourcing then I'd encourage you to find a new verb.

See Cmdlet Verbs on MSDN for more info.

Dan Mork
Good points, cheers!
James Kolpack