Skip to content

Instantly share code, notes, and snippets.

@santisq
Created June 19, 2026 15:55
Show Gist options
  • Select an option

  • Save santisq/e38952ac54de8cacb1ecb7c03ab91edb to your computer and use it in GitHub Desktop.

Select an option

Save santisq/e38952ac54de8cacb1ecb7c03ab91edb to your computer and use it in GitHub Desktop.
using System;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Threading;
public static class Test
{
private const string Script =
"& {param($e) $e::Iterations++; & $MyInvocation.MyCommand.ScriptBlock $e } $args[0]";
public static int Iterations { get; set; }
public static void RunTests(int stacksize)
{
Iterations = 0;
PSRun();
Console.WriteLine($"Iterations: {Iterations}");
Iterations = 0;
PSRunWithThread(stacksize);
Console.WriteLine($"Iterations: {Iterations}");
}
private static void PSRun()
{
using PowerShell ps = GetPSTest();
ps.Invoke();
Console.WriteLine(ps.Streams.Error[0]?.Exception.Message);
}
private static void PSRunWithThread(int stacksize)
{
Thread thread = new(() =>
{
using Runspace rs = RunspaceFactory.CreateRunspace();
rs.ThreadOptions = PSThreadOptions.UseCurrentThread;
rs.Open();
using PowerShell ps = GetPSTest();
ps.Runspace = rs;
ps.Invoke();
Console.WriteLine(ps.Streams.Error[0]?.Exception.Message);
}, stacksize);
thread.Start();
thread.Join();
}
private static PowerShell GetPSTest() => PowerShell
.Create()
.AddScript(Script)
.AddArgument(typeof(Test));
}
Add-Type -Path ./PSStackTest.cs
[Test]::RunTests(20mb)

# The script failed due to call depth overflow.
# Iterations: 9055
# The script failed due to call depth overflow.
# Iterations: 19132
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment