【问题标题】:Global vs script variable全局 vs 脚本变量
【发布时间】:2022-01-21 15:23:18
【问题描述】:

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

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

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

【问题讨论】:

  • 这很奇怪。你在运行 PowerShell 7 吗?
  • 您在同一范围内创建它们。请参阅 Get-Help About_Scope。
  • Powershell 5.1 版本
  • 如果我将其定义为全球性,这有什么关系?
  • @EricKlaus 如果您在顶级范围内(例如交互式提示),这很重要

标签: powershell scope global


【解决方案1】:

这就是 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"

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

【讨论】:

    猜你喜欢
    • 2016-03-03
    • 2016-09-23
    • 2017-07-11
    • 1970-01-01
    • 2013-10-06
    • 2021-10-19
    • 1970-01-01
    • 2021-03-01
    • 2013-11-28
    相关资源
    最近更新 更多