如何在 PowerShell 中配置调用深度?

jum*_*mbo 5 powershell recursion exception

我只是在 PowerShell 中尝试,并在某些测试递归函数中收到有关调用深度设置为 1000 的错误。我在网上查找了一些信息,发现这是由于PowerShell中的错误处理造成的(如果我没猜错的话):

递归深度限制在版本 1 中得到修复。由于处理异常的方式,深度递归在 64 位模式下会导致问题。它导致级联内​​存不足错误。最终结果是我们硬限制了所有平台上的递归深度,以帮助确保脚本可移植到所有平台。- Bruce Payette,PowerShell 联合设计师

我在这里找到的。

另外,我在 MSDN 上发现了这个异常页面,其中指出此限制是可配置的(但我没有找到有关如何执行此操作的任何内容) - 请参阅此处的备注部分。

这个限制怎么设置呢?

jon*_*n Z 4

  • 在PowerShell V1中,最大调用深度为 100:

使用.NET Reflector,我们可以在类代码的这段代码中看到System.Management.ExecutionContext,

internal int IncrementScopeDepth()
{
    using (IDisposable disposable = tracer.TraceMethod("{0}", new object[] { this.scopeDepth }))
    {
        if (this.CurrentPipelineStopping)
        {
            throw new PipelineStoppedException();
        }
        this.scopeDepth++;
        if (this.scopeDepth > 100)
        {
            ScriptCallDepthException exceptionRecord = new
            ScriptCallDepthException(this.scopeDepth, 100);
            tracer.TraceException(exceptionRecord);
            throw exceptionRecord;
        }
        return this.scopeDepth;
    }
}
Run Code Online (Sandbox Code Playgroud)

不可能修改硬编码的 100。

  • 在PowerShell V2中,最大调用深度为 1000

再次查看代码时,似乎没有办法绕过默认的最大调用深度。

  • 在PowerShell V3 (CTP)中,似乎没有最大调用深度(当然,除非您耗尽资源)。此行为已被描述为连接错误,因此在最终版本中可能会发生变化。