Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Global vs script variable

I have defined and assigned both global and script variables. But then when i call global variable, it gets overriden with script variable

$global:myvar = 'global' 
$myvar = 'script'

$global:myvar #I expect here 'global', but it prints 'scipt'
$myvar

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This is how PowerShell Variables are designed to work. Variables your scripts or functions set only last as long as they’re running, when they end, their values go away.

In what you’re doing today, you’re changing the $global scope variable but not running a script or function. You’re effectively in the global scope already.

In order to use those nested scopes, you need to run a script or function, like this script below, called scratch.ps1

#script inherited the previous value

"script: current favorite animal is $MyFavoriteAnimal, inherited"

#now setting a script level variable, which lasts till the script ends
$MyFavoriteAnimal = "fox"

"script: current favorite animal is $MyFavoriteAnimal"

function GetAnimal(){
   #this function will inherit the variable value already set in the script scope
   "function: my favorite animal is currently $MyFavoriteAnimal"

   #now the function sets it's own value for this variable, in the function scope
   $MyFavoriteAnimal = "dog"

   #the value remains changed until the function ends
   "function: my favorite animal is currently $MyFavoriteAnimal"
}

getAnimal

#the function will have ended, so now the script scope value is 'back'
"script: My favorite animal is now $MyFavoriteAnimal"

To access this functionality, you’ll need to use scripts or functions.

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading