Powershell variable scope

<p dir=“ltr”>Hi. I have an interesting problem related to PowerShell variables and it seems scope related. I have a number of scripts that share common names for the variables. I usually follow some kind of standard when naming my variables. These scripts are executed via task scheduler in windows. At any time there can be up to 4 scripts runnining at the same time. It seems that the values of the variables are changing to values in the other scripts variables. For example if script 1 has a variable $a with a value of 1 and script 2 has its own version of $a with a value of 2, at some point in the execution of script 1 and while script 2 is running, the value of $a in script 1 changes to 2. This is a simple example just to explain the concept. Is this scenario possible and what can be done to resolve it. It also seems to be an intermittent problem which makes it harder to trap. I guess it’s because of the rare occasion when both scripts are referring to $a at the same moment in time.</p>

Any variables at are minimum confined to a session. If you have 4 scripts running in 4 separate Powershell sessions, even if 4 sessions are running the same script. The largest scope is Global or Script, but that would still be confined within the session.

With that said, what are the variables referencing? Can you provide examples?

Hi Rob

Thanks for the reply. I won’t be able to send you examples. The variables are used for various purposes but my main concern are the variables that are passed as parameters to calls to insert and update stored procedures in sql. The key of the inserted row is returned to the script and saved into the variable and then the same variable is used as the parameter passed to the update stored procedure to update the row further down the logic in the script. As long as there is no chance that another scripts variable value (with the same name) was being used in the update line. So if this is not possible as you suggested then I must maybe look elsewhere for cases where the update might be going wrong.