Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/extjs/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
了解Powershell变量范围_Powershell_Scope - Fatal编程技术网

了解Powershell变量范围

了解Powershell变量范围,powershell,scope,Powershell,Scope,我试图理解变量是如何保留值和范围的。为此,我创建了两个简单的脚本 低级脚本如下所示 param( $anumber=0 ) function PrintNumber { Write-Host "Number is $anumber" $anumber++ Write-Host "Number is now $anumber" } $scriptPath=(Split-Path -parent $PSCommandPath)+"\" + "calledscrip

我试图理解变量是如何保留值和范围的。为此,我创建了两个简单的脚本

低级脚本如下所示

param(
    $anumber=0
)

function PrintNumber
{
    Write-Host "Number is $anumber"
    $anumber++
    Write-Host "Number is now $anumber"
}
$scriptPath=(Split-Path -parent $PSCommandPath)+"\" + "calledscript.ps1"
#dot source the called script
. $scriptPath 22

for($i=0;$i -lt 10;$i++)
{
    PrintNumber
}
顶层脚本如下所示

param(
    $anumber=0
)

function PrintNumber
{
    Write-Host "Number is $anumber"
    $anumber++
    Write-Host "Number is now $anumber"
}
$scriptPath=(Split-Path -parent $PSCommandPath)+"\" + "calledscript.ps1"
#dot source the called script
. $scriptPath 22

for($i=0;$i -lt 10;$i++)
{
    PrintNumber
}
主脚本“点源”在开始时调用脚本一次,并传入一个值“22”。然后在顶层脚本中调用PrintNumber函数10次。我以为输出会是这样的:

电话号码是22 现在的数字是23

电话号码是23 现在是24号

电话号码是24 现在是25号

但是当调用函数时,数字总是22(输出如下)。为什么每次都会将这个数字重置为22,即使我只输入了一次点源代码脚本,并在那里初始化了22

电话号码是22 现在的数字是23

电话号码是22 现在的数字是23

电话号码是22 现在的数字是23

谢谢


(请忽略任何输入错误)

这是因为变量继承。Technet是这样解释的

A child scope does not inherit the variables, aliases, and functions from
the parent scope. Unless an item is private, the child scope can view the
items in the parent scope. And, it can change the items by explicitly 
specifying the parent scope, but the items are not part of the child scope.

由于脚本是点源代码,因此它创建了一个会话本地变量。当函数访问具有相同名称的变量时,它可以从父作用域读取该变量,但随后它会创建一个本地副本,该副本随后递增并随后销毁。

如果将其定义更改为
$global:anumber
,会发生什么情况?我更改了引用(而不是声明)从$anumber++到$global:anumber++,然后按照我的预期递增。不完全清楚为什么真的!!这绝对是一个范围问题。我不知道太多的细节,但PowerShell中有
local
script
global
变量。因为您从不同的脚本中获取变量,所以默认范围是
script
,递增的值不会持续。谢谢@JonC,但是函数从父范围读取的变量是什么?我在被调用的脚本中只有变量,而没有父变量。另一个问题是如何显式指定父范围?介绍作用域的基本知识。简单的答案是使用诸如$global:anumber或$script:anumber这样的修饰符。您还可以在cmdlet中使用相对修饰符,如
get variable-name anumber-scope 0
,其中0是当前作用域,1是直接父级,2是下一个父级,等等。感谢Jonc,我已经通读了这些内容。现在只需要内心消化。