我有一个递归函数,执行了大约 750 次 - 迭代 XML 文件并进行处理。代码正在使用
Start-Job
运行
以下示例:
$job = Start-Job -ScriptBlock {
function Test-Function {
Param
(
$count
)
Write-Host "Count is: $count"
$count++
Test-Function -count $count
}
Test-Function -count 1
}
输出:
$job | Receive-Job
Count is: 224
Count is: 225
Count is: 226
Count is: 227
The script failed due to call depth overflow.
在我的机器上,深度溢出始终发生在 227。如果我去掉
Start-Job
,我可以达到750~(甚至更高)。我正在使用作业进行批处理。
使用
Start-Job
时有没有办法配置深度溢出值?
这是 PowerShell 作业的限制吗?
我无法回答 PS 5.1 / 7.2 中调用深度溢出限制的具体细节,但您可以基于作业中的队列进行递归。
因此,您不是在函数内进行递归,而是从外部进行递归(尽管仍在工作内)。
这就是它的样子。
$job = Start-Job -ScriptBlock {
$Queue = [System.Collections.Queue]::new()
function Test-Function {
Param
(
$count
)
Write-Host "Count is: $count"
$count++
# Next item to process.
$Queue.Enqueue($Count)
}
# Call the function once
Test-Function -count 1
# Process the queue
while ($Queue.Count -gt 0) {
Test-Function -count $Queue.Dequeue()
}
}
参考:
这不是解决问题的答案,而是提供信息的答案。您可以使用 PowerShell SDK 的
[powershell]
类的实例来代替 Start-Job
,它可以处理更多级别的递归(大量),以防有帮助,这是我的结果:
技术 | 迭代 | PowerShell 版本 | 操作系统 |
---|---|---|---|
|
226~ | 5.1 | Windows 10 |
|
2008~ | 7.2.1 | Linux |
PowerShell 实例 | 4932~ | 5.1 | Windows 10 |
PowerShell 实例 | 11193~ | 7.2.1 | Linux |
$instance = [powershell]::Create().AddScript({
function Test-Function {
Param($Count)
Write-Host "Count is: $count"
$count++
Test-Function -count $count
}
Test-Function -Count 1
})
$async = $instance.BeginInvoke()
while(-not $async.AsyncWaitHandle.WaitOne(200)) { }
$instance.Streams.Information[-1]
$instance.Dispose()