我正在学习 Powershell 中的范围并且有一些问题:
local
修饰符? You can create a new scope by running a script or function, by creating a session, or by starting a new instance of PowerShell. When you create a new scope, the result is a parent scope (the original scope) and a child scope (the scope that you created). ...
Unless you explicitly make the items private, the items in the parent scope are available to the child scope. However, items that you create and change in the child scope do not affect the parent scope, unless you explicitly specify the scope when you create the items.
但是当我尝试以下操作时:
PS> $Name = "John"
PS> Powershell.exe
PS>echo $Name // No Output
从上面的引用看来,“启动一个新的 powershell 实例”是一个子作用域,所以父作用域中的所有项目都应该在那里可见。有人可以解释一下吗?
最佳答案
从后一个问题开始:
作用域与函数和调用的脚本(cmdlet)一起使用,例如:
Function Test {
$Test++
Write-Host 'Local:' $Test
}
$Test = 5
Test
Write-Host 'Global:' $Test
返回:Local: 6
Global: 5
和:Function Test {
$Global:Test++
Write-Host 'Local:' $Test
}
$Test = 5
Test
Write-Host 'Global:' $Test
返回:Local: 6
Global: 6
或者,如果您将该函数放在脚本中(例如 MyScript.ps1
):$Test = 5
.\MyScript.ps1
Write-Host $Test # $Test is unaffected unless you use the $Global scope in your script
除非您 Dot-Source,否则将返回与上述基本相同的结果您的脚本将在当前范围内运行的位置:$Test = 5
. .\MyScript.ps1
Write-Host $Test # $Test might be affected by MyScript.ps1 if you just use $Test
对于你正在做的事情:您正在创建一个完整的新 PowerShell session (使用
Powershell.exe
),它将以新的变量列表开始。请注意,如果您
exit
,您将再次看到初始变量。来自新 session :PS C:\> $Name = "John"
PS C:\> Powershell.exe
Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.
Try the new cross-platform PowerShell https://aka.ms/pscore6
PS C:\> Write-Host 'New session' $Name
New session
PS C:\> Exit
PS C:\> Write-Host 'Initial session' $Name
Initial session John
关于第一个问题,我不认为有很多应用程序需要明确引用$Local
范围,但给你一个例子,你可以使用它:$Test = 5
Function Test {
Write-Host ($Local:Test++)
}
Test
在上面的例子中 unary increment operator将以 0
开头如果您明确使用 $Local
范围(实际上你从一个空的局部变量开始,它将转换为 0
)和 5
如果您省略 $Local
您将继承 $Test
副本的范围父作用域之外的变量。
关于.net - 关于 Powershell 中的作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63555454/