简体   繁体   中英

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

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.

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM