PowerShell:调用包含下划线变量的脚本块

4
我通常会按照以下步骤调用包含 $_ 的脚本块:
$scriptBlock = { $_ <# do something with $_ here #> }
$theArg | ForEach-Object $scriptBlock

实际上,我正在创建一个管道,它将在Foreach-Object函数调用内给$_赋值。

但是,当查看LINQ模块的源代码时,它定义并使用以下函数来调用委托:

# It is actually surprisingly difficult to write a function (in a module)
# that uses $_ in scriptblocks that it takes as parameters. This is a strange
# issue with scoping that seems to only matter when the function is a part
# of a module which has an isolated scope.
# 
# In the case of this code:
# 1..10 | Add-Ten { $_ + 10 }
#
# ... the function Add-Ten must jump through hoops in order to invoke the
# supplied scriptblock in such a way that $_ represents the current item
# in the pipeline.
#
# Which brings me to Invoke-ScriptBlock.
# This function takes a ScriptBlock as a parameter, and an object that will
# be supplied to the $_ variable. Since the $_ may already be defined in
# this scope, we need to store the old value, and restore it when we are done.
# Unfortunately this can only be done (to my knowledge) by hitting the
# internal api's with reflection. Not only is this an issue for performance,
# it is also fragile. Fortunately this appears to still work in PowerShell
# version 2 through 3 beta.
function Invoke-ScriptBlock {
[CmdletBinding()]

    param (
        [Parameter(Position=1,Mandatory=$true)]
        [ScriptBlock]$ScriptBlock,

        [Parameter(ValueFromPipeline=$true)]
        [Object]$InputObject
    )

    begin {
            # equivalent to calling $ScriptBlock.SessionState property:
            $SessionStateProperty = [ScriptBlock].GetProperty('SessionState',([System.Reflection.BindingFlags]'NonPublic,Instance'))
            $SessionState = $SessionStateProperty.GetValue($ScriptBlock, $null)
        }
    }
    process {
        $NewUnderBar = $InputObject
        $OldUnderBar = $SessionState.PSVariable.GetValue('_')
        try {
            $SessionState.PSVariable.Set('_', $NewUnderBar)
            $SessionState.InvokeCommand.InvokeScript($SessionState, $ScriptBlock, @())
        }
        finally {
            $SessionState.PSVariable.Set('_', $OldUnderBar)
        }
    }
}

我觉得这有点低级了。有没有一个推荐、安全的方法来做这件事?


2
另一种方法是动态添加参数块:$ScriptBlock = [scriptblock]::Create("param(`$_)$ScriptBlock") - Mathias R. Jessen
Mathias的评论应该是一个答案。这正是我处理它的方式。 - Robert Kozak
4
这跟"$ScriptBlock.InvokeWithContext($null, (New-Object PSVariable '_',$value), $null)"有什么不同吗?——只是问一下。 - Tahir Hassan
2
http://blogs.msdn.com/b/sergey_babkins_blog/archive/2014/10/30/calling-the-script-blocks-in-powershell.aspx - Tahir Hassan
1个回答

3
您可以使用 & 符号调用脚本块,无需使用 Foreach-Object。
$scriptblock = {## whatever}
& $scriptblock

@(1,2,3) | % { & {write-host $_}}

传递参数:

$scriptblock = {write-host $args[0]}
& $scriptblock 'test'

$scriptBlock = {param($NamedParam) write-host $NamedParam}
& $scriptBlock -NamedParam 'test'

如果您要在Invoke-Command中使用此内容,您还可以使用$using构造。
$test = 'test'
$scriptblock = {write-host $using:test}

1
请再次阅读问题。我已经知道了。我说的是包含$ _变量的特殊脚本块。 - Tahir Hassan
我已经阅读了你的问题并进行了测试。无论脚本块是否包含管道变量,它都能正常工作。我已更新答案。 - Adam Bertram
2
如果你需要在模块之间跳转,那么它将无法工作。链接 - user4003407
1
在我的电脑上,& { $_ } 10 没有返回任何值,但是 & { param($x) $x } 10 正确地返回了值 10。我想询问一下有关调用管道变量($_)脚本块的推荐方法。 - Tahir Hassan
1
我明白了。你是在问如何将参数传递到脚本块中?这是完全不同的问题。没有必要因为你对术语的误解而对我的答案进行负评。我已经更新了我的答案。 - Adam Bertram

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接