当并行处于活动状态时,我在 ForEach-Object 内使用用户定义函数时遇到一些困难:
function Add([Int]$number) {
Write-Output "Run for $number"
}
1..4 | ForEach-Object -Parallel {
Add -number $_
}
我收到一条错误消息:
术语“添加”不被识别为 cmdlet、函数、
脚本文件,或可执行程序。检查姓名的拼写,或者
如果包含路径,请验证该路径是否正确,然后重试。
我相信在内部使用 UDF 是一种常见的主动行为foreach环形。你有什么解决方法吗? $using: 仅适用于变量,不适用于函数,对吧?
您可以在范围内定义该函数平行块(运行空间):
1..4 | ForEach-Object -Parallel {
function Add([Int]$number) {
Write-Output "Run for $number"
}
Add -number $_
}
或者存储函数的定义,然后将其传递到您的函数的范围平行块 and 点源它 https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_operators?view=powershell-7.2#dot-sourcing-operator-:
function Add([Int]$number) {
Write-Output "Run for $number"
}
$def = "function Add { ${function:Add} }"
1..4 | ForEach-Object -Parallel {
. ([scriptblock]::Create($using:def))
Add -number $_
}
Linked mklement0 的有用答案 https://stackoverflow.com/questions/61273189/how-to-pass-a-custom-function-inside-a-foreach-object-parallel显示了在并行范围内定义函数的更清晰的替代方案。强烈推荐这个方法,更容易阅读和理解:
function Add([Int]$number) {
Write-Output "Run for $number"
}
$def = ${function:Add}.ToString()
1..4 | ForEach-Object -Parallel {
$function:Add = $using:Def
Add -number $_
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)