全局与脚本变量

Global vs script variable

我已经定义并分配了全局变量和脚本变量。但是当我调用全局变量时,它会被脚本变量覆盖

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

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

PowerShell 变量就是这样设计的。您的脚本或函数设置的变量只在 运行 期间有效,当它们结束时,它们的值就会消失。

在您今天所做的事情中,您更改的是 $global 范围变量,而不是 运行ning 脚本或函数。您实际上已经处于全局范围内。

为了使用这些嵌套范围,您需要 运行 脚本或函数,如下面的脚本,名为 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"

要访问此功能,您需要使用脚本或函数。