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 'script'
$myvar
CodePudding user response:
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 its 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.