除非您将其声明到特定范围,否则任何变量都将在本地范围内自动创建。Script
是脚本文件基础中命令的本地范围,function 是函数内命令的本地范围。全局是会话的“本地范围”(例如,您直接在控制台中写入的命令)。前任:
MyScript.ps1
$myscriptvar = "This is in a local SCRIPT scope"
function test {
$myfuncvar = "This is in the local scope for the function"
#I can READ $myscriptvar in here, but if I define it (ex $myscriptvar = 2),
#the change will exist in a LOCAL variable ($function:myscriptvar) in the function only.
}
test
安慰
$myglobalvar = @"
This is in the global scope and can be read by
the script and the function inside the script, but any changes will be saved in
their local scope if not specified like $global:mygloblvar
"@
.\MyScript.ps1
因此,默认情况下,所有变量都是在“本地”范围内创建的,它只取决于您定义它的位置(在控制台、脚本文件、函数中)。
使用脚本编辑示例:
无标题2.ps1
"In script2, `$myvar is: $:myvar"
"In script2, `$script:myvar is: $script:myvar"
$myvar = "lol"
无标题1.ps1
$myvar = "Hey"
.\Untitled2.ps1
$myvar
安慰
PS > .\Untitled1.ps1
In script2 , $myvar is: Hey
In script2 , $script:myvar is:
Hey