如何在 ForEach-Object -Parallel 中传递自定义函数 [英] How to pass a custom function inside a ForEach-Object -Parallel

查看:41
本文介绍了如何在 ForEach-Object -Parallel 中传递自定义函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找不到传递函数的方法.只是变量.

I can't find a way to pass the function. Just variables.

没有将函数放入 ForEach 循环中的任何想法?

Any ideas without putting the function inside the ForEach loop?

function CustomFunction {
    Param (
        $A
    )
    Write-Host $A
}

$List = "Apple", "Banana", "Grape" 
$List | ForEach-Object -Parallel {
    Write-Host $using:CustomFunction $_
}

推荐答案

解决方案并不像人们希望的那么简单:

The solution isn't quite as straightforward as one would hope:

function CustomFunction {
    Param ($A)
    "[$A]"
}

# Get the function's definition *as a string*
$funcDef = $function:CustomFunction.ToString()

"Apple", "Banana", "Grape"  | ForEach-Object -Parallel {
    # Define the function inside this thread...
    $function:CustomFunction = $using:funcDef
    # ... and call it.
    CustomFunction $_
}

  • 这种方法是必要的,因为 - 除了当前位置(工作目录)和环境变量(适用于进程范围)之外 - ForEach-Object -Parallel 创建的线程执行看不到调用者的状态,尤其是变量和函数(也看不到自定义 PS 驱动器和导入的模块).

    • This approach is necessary, because - aside from the current location (working directory) and environment variables (which apply process-wide) - the threads that ForEach-Object -Parallel creates do not see the caller's state, notably neither with respect to variables nor functions (and also not custom PS drives and imported modules).

      从 PowerShell 7.0 开始,正在 GitHub 上讨论增强功能支持将调用者的状态按需复制到线程,这将使调用者的功能可用.

      As of PowerShell 7.0, an enhancement is being discussed on GitHub to support copying the caller's state to the threads on demand, which would make the caller's functions available.

      请注意,在没有辅助的情况下凑合.$funcDef 变量并尝试使用 $function:CustomFunction = $using:function:CustomFunction 重新定义函数很诱人,但是 $function:CustomFunction是一个脚本块,明确禁止使用带有 $using: 范围说明符的脚本块.

      Note that making do without the aux. $funcDef variable and trying to redefine the function with $function:CustomFunction = $using:function:CustomFunction is tempting, but $function:CustomFunction is a script block, and the use of script blocks with the $using: scope specifier is explicitly disallowed.

      $function:CustomFunction命名空间变量符号的一个实例,它允许您获取一个函数(它的body作为一个[scriptblock]实例)和set(定义)它,通过分配 [scriptblock] 或包含函数体的字符串.

      $function:CustomFunction is an instance of namespace variable notation, which allows you to both get a function (its body as a [scriptblock] instance) and to set (define) it, by assigning either a [scriptblock] or a string containing the function body.

      这篇关于如何在 ForEach-Object -Parallel 中传递自定义函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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