还有一个...嵌套的foreach-object中的父变量

时间:2019-07-10 06:46:43

标签: powershell

为什么不起作用?

1..2 | % {
    3..4 | % {
        Get-Variable -Name '_' -Scope 0
        Get-Variable -Name '_' -Scope 1 # <===
    }
    Get-Variable -Name '_' -Scope 0
}

1 个答案:

答案 0 :(得分:0)

由于%ForEach-Object)没有引入新的作用域,因此无法正常工作。

以下是证明:$x在相同范围内已更改,在父级中不会更改:

$x = 'old'
1 | % { $x = 'new' }
$x

如果需要范围,则可以使用结构&{process{...}}代替ForEach-Object

1..2 | & {process{
    3..4 | & {process{
        Get-Variable -Name '_' -Scope 0
        Get-Variable -Name '_' -Scope 1 # <===
    }}
    Get-Variable -Name '_' -Scope 0
}}

以上方法按预期工作。

注意:&{process{...}}(新作用域)或.{process{...}}(相同作用域)也比%快。