gpt4 book ai didi

powershell - 如何在 ForEach-Object -Parallel 中传递自定义函数

转载 作者:行者123 更新时间:2023-12-02 22:13:34 29 4
gpt4 key购买 nike

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

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

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

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

enter image description here

最佳答案

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

# Sample custom function.
function Get-Custom {
Param ($A)
"[$A]"
}

# Get the function's definition *as a string*
$funcDef = ${function:Get-Custom}.ToString()

"Apple", "Banana", "Grape" | ForEach-Object -Parallel {
# Define the function inside this thread...
${function:Get-Custom} = $using:funcDef
# ... and call it.
Get-Custom $_
}
注: This answer包含一个类似的解决方案,用于在 ForEach-Object -Parallel 中使用调用者范围内的脚本 block 。脚本 block 。
  • 备注 : 如果您的函数是在一个模块中定义的,该模块位于 module-autoloading 已知位置之一。功能,您的函数调用将按原样使用 ForEach-Object -Parallel ,无需额外的努力 - 但每个线程都会产生(隐式)导入模块的成本。
  • 上述方法是必要的,因为 - 除了当前位置(工作目录)和环境变量(适用于进程范围)之外 - ForEach-Object -Parallel 的线程created 看不到调用者的状态,尤其是关于变量和函数(也不是自定义 PS 驱动器和导入模块)。
  • 更新:js2010's helpful answer显示了一个更直接的解决方案,它通过 System.Management.Automation.FunctionInfo 实例,通过 Get-Command 获得,可以直接用&调用.唯一需要注意的是,原始函数应该没有副作用,即应该完全基于参数或管道输入进行操作,而不依赖于调用者的状态,尤其是它的变量,因为这可能会导致线程安全问题。上面的字符串化技术隐式地防止了对调用者状态的任何有问题的引用,因为函数体是在每个线程的上下文中重建的。

  • 从 PowerShell 7.1 开始,GitHub issue #12240 中正在讨论一项增强功能。支持按需将调用者的状态复制到线程,这将使调用者的函数可用。

  • 请注意,没有辅助就凑合。 $funcDef变量并尝试使用 ${function:Get-Custom} = ${using:function:Get-Custom} 重新定义函数很诱人,但是 ${function:Get-Custom}是一个脚本 block ,并且使用脚本 block 与 $using:明确禁止范围说明符。
  • 但是,${function:Get-Custom} = ${using:function:Get-Custom}将与 Start-Job 一起使用;见 this answer例如。
  • 它也适用于 Start-ThreadJob , 你甚至可以做 & ${using:function:Get-Custom} $_ , 因为 ${using:function:Get-Custom}被保留为脚本 block (与 Start-Job 不同,它被反序列化为字符串,这本身就是令人惊讶的行为 - 请参阅 GitHub issue #11698 )。但是,尚不清楚设计是否支持此行为,因为它受到上述相同的潜在跨线程问题的影响。
  • ${function:Get-Custom}namespace variable notation 的一个实例,它允许您通过分配 [scriptblock] 来获取一个函数(它的主体为 [scriptblock] 实例)并设置(定义)它。或包含函数体的字符串。

    关于powershell - 如何在 ForEach-Object -Parallel 中传递自定义函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61273189/

    29 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com