I have difficulty trying to find an answer that solves this issue online.
I have a script which runs all my other scripts in a particular order.
$x=0;
$z=0;
cd *file path* ;
.\filename1.ps1 ; write-host "$x text $z text";
.\filename2.ps1 ; write-host "$x text $z text";
In each of these scripts I have options that will add 1 to either variable $x or variable $z
$a=Read-Host
if ($a -eq "Option One") {$x = $x+1}
elseif ($a -eq "Option Two") {$z = $z+1}
else {Write-Host "Not a valid option" ; .\filenameX.ps1}
The issue is that the script that runs all these scripts won't recognise the change in variable. How do I fix this?
The naïve answer is to "dot-source" these scripts, i.e. to invoke them with operator .
Using . executes the scripts in the caller's variable scope, so that top-level modifications of $x an $z will be visible even after .\filename1.ps1 and .\filename2.ps1 have completed.
# Note the `. ` preceding the file path - the space after "." is mandatory
. .\filename1.ps1 ; "$x text $z text"
. .\filename2.ps1 ; "$x text $z text"
Note, however, that all top-level variables created or modified in . -invoked scripts will be visible to the caller.
For more on variable scopes in PowerShell, see this answer.
Better encapsulated options are to either (a) output modified values or, less commonly, (b) use of [ref] parameters to pass by-reference variables to scripts - whose parameters must be declared and assigned to accordingly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With