Currently I have two Powershell scripts, main.ps1 and data.ps1, which share a global variable called $Global:SharedValues. The global variable is initialised in the data.ps1 script and is then used within the primary script, main.ps1. This all works perfectly.
However, the size of the script, data.ps1, is growing and it’s maintenance is becoming less convenient, which is why I’d now like to split the contents up over multiple files. However, I’d like to be able to include the scripts dynamically so that I don’t need to manually add a . include into the main.ps1 each time a new data script is created.
I have tried two approaches to dynamically include the scripts, Invoke-Expression $data and powershell.exe $data. In both cases the data scripts are run, however changes made to the global variable are ignored – so I gather the scripts are run in a separate memory instance!?
Is it possible to share the global variable between all the scripts? Can I somehow pass the variable via a pipeline or something to the dynamically included scripts?
>Solution :
Yes, it is possible to share the global variable between multiple PowerShell scripts when you include them dynamically. However, you need to ensure that the scripts are executed in the same PowerShell session or runspace.
Here’s an approach you can follow:
Create a main script that initializes the global variable and imports all the required data scripts.
Use the Dot Source operator ( . ) to import the data scripts into the same session or runspace.
An example implementation:
main.ps1-
# Initialize the global variable
$Global:SharedValues = @{}
# Get all data script files in the "data" folder
$dataScriptFiles = Get-ChildItem -Path "data" -Filter "*.ps1"
# Dot-source each data script file
foreach ($file in $dataScriptFiles) {
. $file.FullName
}
# Use the $Global:SharedValues variable
Write-Host "Shared Values: $($Global:SharedValues)"
data\data1.ps1
# Modify the global variable
$Global:SharedValues.Add("Key1", "Value1")
data\data2.ps1
# Modify the global variable
$Global:SharedValues.Add("Key2", "Value2")
If you want to maintain the data scripts in separate folders or have a more complex file structure, you can modify the Get-ChildItem command to search for the files accordingly.