为什么不起作用?
1..2 | % {
3..4 | % {
Get-Variable -Name '_' -Scope 0
Get-Variable -Name '_' -Scope 1 # <===
}
Get-Variable -Name '_' -Scope 0
}
答案 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{...}}
(相同作用域)也比%
快。