PowerShell 中的变量范围 [英] Variable scoping in PowerShell

查看:27
本文介绍了PowerShell 中的变量范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PowerShell 的一个遗憾是函数和脚本块是动态范围的.

A sad thing about PowerShell is that function and scriptblocks are dynamically scoped.

但让我感到惊讶的另一件事是变量在内部作用域内表现为写时复制.

But there is another thing that surprised me is that variables behave as a copy-on-write within an inner scope.

$array=@("g")
function foo()
{
    $array += "h"
    Write-Host $array
}

& {
    $array +="s"
    Write-Host $array
}
foo

Write-Host $array

输出为:

g s
g h
g

这使得动态范围的痛苦减少了一点.但是如何避免写时复制?

Which makes dynamic scoping a little bit less painful. But how do I avoid the copy-on-write?

推荐答案

您可以使用 范围修饰符*-Variable cmdlet.

You can use scope modifiers or the *-Variable cmdlets.

范围修饰符是:

  • global 用于在最外层范围(例如交互式 shell)访问/修改
  • script 用于在运行脚本(.ps1 文件)范围内访问/修改.如果不运行脚本,则作为 global 运行.
  • global used to access/modify at the outermost scope (eg. the interactive shell)
  • script used on access/modify at the scope of the running script (.ps1 file). If not running a script then operates as global.

(对于 *-Variable cmdlet 的 -Scope 参数,请参阅帮助.)

(For the -Scope parameter of the *-Variable cmdlets see the help.)

例如.在你的第二个例子中,直接修改全局 $array:

Eg. in your second example, to directly modify the global $array:

& {
  $global:array +="s"
  Write-Host $array
}

有关详细信息,请参阅帮助主题 about_scopes.

For more details see the help topic about_scopes.

这篇关于PowerShell 中的变量范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆