带有参数化脚本块的 PowerShell 函数 [英] PowerShell function with parameterized script block

查看:40
本文介绍了带有参数化脚本块的 PowerShell 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个 PowerShell 函数来枚举一些数据,并在所有出现时触发一个脚本块.

I want to create a PowerShell function that enumerates some data, and fire a script block on all occurrences.

现在我有(这不是实际的代码,但它说明了我的问题):

By now I have (this is not the actual code, but it illustrates my issue):

function Invoke-TenTimes
{
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory=$true, Position=0)]
        [ScriptBlock]$Action
    )
    process
    {
        $digits = 0..10
        $digits | % {
            $Action.Invoke($_);
        }
    }
}

我把这个函数放在我的模块中.但是,当我打电话时我没有得到任何结果:

I put this function in my module. However, I don't get any result when I call:

Invoke-TenTimes { $_ }

输出为空白(不显示任何内容).

The output is blank (nothing is displayed).

如果我打电话

Invoke-TenTimes { $_ -eq $null }

我得到十个true.事实上,我看到 $_ 为空.

I get ten true. In fact, I see that $_ is null.

填充 $_ 的正确方法是什么?

What is the proper way to populate the $_ ?

让我发疯的是,如果我把这个函数和调用放在同一个 ps1 文件中,它就可以工作(但我想按需传递脚本块):

What is driving me crazy, is that if I put this function and the call in the same ps1 file, it works (but I want to pass script block on demand):

function Invoke-TenTimes
{
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory=$true, Position=0)]
        [ScriptBlock]$Action
    )
    process
    {
        $digits = 0..10
        $digits | % {
            $Action.Invoke($_);
        }
    }
}


Invoke-TenTimes { $_ }

推荐答案

这是一个作用域问题,传入的脚本块属于与执行位置不同的作用域.如果传入的脚本块不必从其上下文中引用变量,您可以简单地克隆脚本块以强制它在您运行它的范围内.与

this is a scoping issue with the passed in scriptblock belonging to a different scope than where it is executing. If the passed in scriptblock won't have to refer to variables from its context you can simply clone the scriptblock to force it to be in the scope you are running it. with

$action = [scriptblock]::Create($action)

有趣的是,它最初只在 ACCIDENT 中起作用.它从脚本块所属的父作用域获取 $_ ,它恰好在你的 foreach-object 内部,这很好.

the interesting thing is it only worked in the first place by ACCIDENT. it was getting the $_ from the parent scope of where the scriptblock belonged which happened to be inside you foreach-object which was good.

但是使用您的原始版本,然后运行此

however take your original version, and then run this

"gotcha" | % {
Invoke-TenTimes {  $_ }
}

你会看到你会得到 10 次 gotcha,因为 $_ 在你的调用者范围内不是空的,而是某种东西.

and you'll see you'll get gotcha 10 times, because $_ is not null in your callers scope, but is something.

这篇关于带有参数化脚本块的 PowerShell 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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