全局变量与脚本变量

Eri*_*aus 1 powershell scope global

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

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

$global:myvar #I expect here 'global', but it prints 'script'
$myvar
Run Code Online (Sandbox Code Playgroud)

Fox*_*loy 6

这就是 PowerShell 变量的工作原理。您的脚本或函数设置的变量仅在运行时持续存在,当它们结束时,它们的值就会消失。

在您今天所做的事情中,您正在更改 $global 作用域变量,但不运行脚本或函数。您实际上已经处于全球范围内。

为了使用这些嵌套作用域,您需要运行一个脚本或函数,如下所示的脚本,称为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"
Run Code Online (Sandbox Code Playgroud)

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

在此输入图像描述