3

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?

Otto Evans
  • 33
  • 3

2 Answers2

3

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.

mklement0
  • 382,024
  • 64
  • 607
  • 775
  • 1
    I believe I figured it out. Is this what you meant? Shared script: `return [PSCustomObject]@{ Name = 'aName'; Ip = 'anIP'; Status = 'aStatus' }`. Other scripts: `$a = .\Common.ps1; $a.Name; $a.Ip; $a.Status`. – GeorgesZ May 14 '21 at 14:03
  • Yes, that's what I meant with respect to encapsulation option (a), @GeorgesZ. – mklement0 May 14 '21 at 14:06
0

If you define you x (and z) variable with a global scope outside your scripts like this: $global:x=0. You can increment it inside your scripts like this: $global:x = $global:x + 1

Alexxx
  • 101