Skip to content
ConsoleMonster

Live runs

Run a script block for many items in parallel with a live view, re-run a command with Watch-Console, and watch Pester tests as they run.

Three commands turn long-running work into a live view on an interactive console and into plain lines everywhere else: Invoke-ConsoleRun for many items, Watch-Console for a command you want to see change, and Invoke-ConsolePester for tests. Each writes ordinary PowerShell output when it ends, so it fits into a script like the commands it replaces.

Forty servers, eight at a time

Invoke-ConsoleRun runs a script block for every item, here in parallel with a time limit. Three servers fail and one hangs; the run keeps going, and the failures are listed when it ends.

Invoke-ConsoleRun -Parallel 100×2424-bitFull
Install-Module ConsoleMonster -Scope CurrentUser
PowerShellparallel.ps1View on GitHub
# Forty servers, eight at a time: three fail and one hangs past the four-second limit.
$servers = 1..40 | ForEach-Object { 'web{0:d2}' -f $_ }
$run = @{ Parallel = $true; ThrottleLimit = 8; TimeoutSeconds = 4; Title = 'Patching' }
$results = $servers | Invoke-ConsoleRun @run -ErrorAction SilentlyContinue {
    Start-Sleep -Milliseconds (500 + ([int] $_.Substring(3) * 137) % 900)
    if ($_ -in 'web13', 'web26', 'web39') { throw "$_ did not come back" }
    if ($_ -eq 'web22') { Start-Sleep -Seconds 10 }
    "$_ patched"
}
Full program
Import-Module ConsoleMonster

# Forty servers, eight at a time: three fail and one hangs past the four-second limit.
$servers = 1..40 | ForEach-Object { 'web{0:d2}' -f $_ }
$run = @{ Parallel = $true; ThrottleLimit = 8; TimeoutSeconds = 4; Title = 'Patching' }
$results = $servers | Invoke-ConsoleRun @run -ErrorAction SilentlyContinue {
    Start-Sleep -Milliseconds (500 + ([int] $_.Substring(3) * 137) % 900)
    if ($_ -in 'web13', 'web26', 'web39') { throw "$_ did not come back" }
    if ($_ -eq 'web22') { Start-Sleep -Seconds 10 }
    "$_ patched"
}

Run: pwsh ./parallel.ps1

Terminal
dotnet new console -n ParallelRun
cd ParallelRun
dotnet add package ConsoleMonster
C#Program.csView on GitHub
// Forty servers patched eight at a time. Three fail and one hangs past the four-second limit;
// the view lists the failures and the results keep them for the rest of the program.
IEnumerable<string> servers = Enumerable.Range(1, 40)
    .Select(n => "web" + n.ToString("00", CultureInfo.InvariantCulture));
IReadOnlyList<RunResult<string, string>> results = await ConsoleRun.ForEachAsync(
    servers,
    async (server, cancel) => {
        int number = int.Parse(server.Substring(3), CultureInfo.InvariantCulture);
        // … 7 more lines in the full program
        return server + " patched";
    },
    new RunOptions { ThrottleLimit = 8, Timeout = TimeSpan.FromSeconds(4), Title = "Patching" });
Full program
using System.Globalization;
using ConsoleMonster.Live;

// Forty servers patched eight at a time. Three fail and one hangs past the four-second limit;
// the view lists the failures and the results keep them for the rest of the program.
IEnumerable<string> servers = Enumerable.Range(1, 40)
    .Select(n => "web" + n.ToString("00", CultureInfo.InvariantCulture));
IReadOnlyList<RunResult<string, string>> results = await ConsoleRun.ForEachAsync(
    servers,
    async (server, cancel) => {
        int number = int.Parse(server.Substring(3), CultureInfo.InvariantCulture);
        await Task.Delay(500 + number * 137 % 900, cancel);
        if (number % 13 == 0) {
            throw new InvalidOperationException(server + " did not come back");
        }
        if (number == 22) {
            await Task.Delay(TimeSpan.FromSeconds(10), cancel);
        }
        return server + " patched";
    },
    new RunOptions { ThrottleLimit = 8, Timeout = TimeSpan.FromSeconds(4), Title = "Patching" });

Run: dotnet run

The recording ran the PowerShell script. This C# program does the same with the library and compiles as shown; its timings are its own.

Terminal
dotnet new console -n ParallelRun
cd ParallelRun
dotnet add package ConsoleMonster
C# fluentProgram.cs
// Forty servers patched eight at a time. Three fail and one hangs past the four-second limit;
// the view lists the failures and the results keep them for the rest of the program.
IEnumerable<string> servers = Enumerable.Range(1, 40)
    .Select(n => "web" + n.ToString("00", CultureInfo.InvariantCulture));
IReadOnlyList<RunResult<string, string>> results = await ConsoleRun.ForEachAsync(
    servers,
    async (server, cancel) =>
    {
        int number = int.Parse(server.Substring(3), CultureInfo.InvariantCulture);
        await Task.Delay(500 + number * 137 % 900, cancel);
        if (number % 13 == 0)
        {
            throw new InvalidOperationException(server + " did not come back");
        }

        if (number == 22)
        {
            await Task.Delay(TimeSpan.FromSeconds(10), cancel);
        }

        return server + " patched";
    },
    options =>
    {
        options.ThrottleLimit(8).Timeout(TimeSpan.FromSeconds(4)).Title("Patching");
    });
Full program
using System.Globalization;
using ConsoleMonster.Live;

// Forty servers patched eight at a time. Three fail and one hangs past the four-second limit;
// the view lists the failures and the results keep them for the rest of the program.
IEnumerable<string> servers = Enumerable.Range(1, 40)
    .Select(n => "web" + n.ToString("00", CultureInfo.InvariantCulture));
IReadOnlyList<RunResult<string, string>> results = await ConsoleRun.ForEachAsync(
    servers,
    async (server, cancel) =>
    {
        int number = int.Parse(server.Substring(3), CultureInfo.InvariantCulture);
        await Task.Delay(500 + number * 137 % 900, cancel);
        if (number % 13 == 0)
        {
            throw new InvalidOperationException(server + " did not come back");
        }

        if (number == 22)
        {
            await Task.Delay(TimeSpan.FromSeconds(10), cancel);
        }

        return server + " patched";
    },
    options =>
    {
        options.ThrottleLimit(8).Timeout(TimeSpan.FromSeconds(4)).Title("Patching");
    });

Run: dotnet run

The recording ran the PowerShell script. This C# program does the same with the library and compiles as shown; its timings are its own.

What the run view shows

  • A summary bar: done of total, the percentage, the time left (estimated from the time so far), and counters for passed, failed, skipped and running items. Counters keep their order, and zeros are dimmed rather than hidden, so the line does not jump.
  • A cell map: one symbol per item in its status colour, so a run of hundreds of items still fits on a few rows.
  • The items running now, with how long each has been running.
  • The failures, listed with their messages when the run ends. An item that runs past -TimeoutSeconds is stopped and counted as failed.

Without -Parallel the items run one at a time in the caller's scope, as with ForEach-Object. With it, up to -ThrottleLimit items run at a time in their own runspaces on Windows PowerShell 5.1 and PowerShell 7; pass the caller's variables with $using:name. In redirected output, CI and jobs, the view becomes one line per finished item and a summary.

-RetryCount 2 -RetryDelaySeconds 5 runs a failed or timed-out item again, up to twice, five seconds apart. Only its last attempt's output and errors are kept; while it retries its cell turns to the warning colour, the running list says retry 1 of 2, and the summary counts retried items. In C# the same options are RunOptions.RetryCount and RetryDelay, and each RunResult reports its Attempts.

The summary bar and the cell map are widgets of their own, for your own views:

$states = @('Pass') * 28 + @('Fail') * 2 + @('Warn') + @('Running') * 4
New-ConsoleRows -Gap 1 -Content {
    New-ConsoleSummaryBar -Value 31 -Total 40 -ElapsedSeconds 42 -Counter ([ordered] @{ passed = 28; failed = 2; warnings = 1 })
    New-ConsoleCellMap -InputObject $states -Count 40
} | Show-Console

In C#, ConsoleRun.ForEachAsync runs the same view around any async work, and SummaryBar and CellMap are in ConsoleMonster.Widgets.

Which run API?

Invoke-ConsoleRun, ConsoleRun.ForEachAsyncStart-ConsoleRun, LiveRun
Who runs the workConsoleMonster runs your script block or async body for each item, with throttling, timeouts and retriesYour script or application schedules it; ConsoleMonster only monitors and never changes results
Finished itemsStay on one screen as cells; failures are listed when the run endsPrint once into scrollback above a dashboard of bounded height
Use it forRunning a script block over many items, one at a time or in parallelWork already running elsewhere (jobs, worker threads, your own scheduler), or runs too long to keep on one screen
PagesLive runsLarge runs

A command as a live view

Watch-Console runs a script block every few seconds and shows its latest output; -Differences marks what changed since the last run.

Watch-Console -Differences 96×1424-bitFull
Install-Module ConsoleMonster -Scope CurrentUser
PowerShellwatch.ps1View on GitHub
# The mail queues every 1.5 seconds; -Differences marks the cells that changed since the last run.
$script:tick = 0
Watch-Console -Title 'Mail queues' -PollIntervalSeconds 1.5 -Count 6 -Differences {
    $script:tick++
    $servers = 'MX01', 'MX02', 'MX03', 'MX04'
    for ($i = 0; $i -lt $servers.Count; $i++) {
        $load = ($script:tick * 7 + $i * 3) % 11
        [pscustomobject] @{
            Server    = "$($servers[$i]).evotec.xyz"
            Queued    = $load * 4
            Deferred  = if ($i -eq 2) { 12 + $script:tick * 5 } else { $load % 3 }
            Delivered = 1200 + $script:tick * 85 + $load * 9
            Status    = if ($i -eq 2 -and $script:tick -gt 2) { 'Warn' } else { 'Pass' }
        }
    }
}
Full program
Import-Module ConsoleMonster

# The mail queues every 1.5 seconds; -Differences marks the cells that changed since the last run.
$script:tick = 0
Watch-Console -Title 'Mail queues' -PollIntervalSeconds 1.5 -Count 6 -Differences {
    $script:tick++
    $servers = 'MX01', 'MX02', 'MX03', 'MX04'
    for ($i = 0; $i -lt $servers.Count; $i++) {
        $load = ($script:tick * 7 + $i * 3) % 11
        [pscustomobject] @{
            Server    = "$($servers[$i]).evotec.xyz"
            Queued    = $load * 4
            Deferred  = if ($i -eq 2) { 12 + $script:tick * 5 } else { $load % 3 }
            Delivered = 1200 + $script:tick * 85 + $load * 9
            Status    = if ($i -eq 2 -and $script:tick -gt 2) { 'Warn' } else { 'Pass' }
        }
    }
}

Run: pwsh ./watch.ps1

C#Program.csView on GitHub
// The same synthetic queue snapshots as watch.ps1; a real provider supplies these rows instead.
ConsoleWatch.Run(
    tick =>
    {
        string[] names = { "MX01", "MX02", "MX03", "MX04" };
        var rows = Enumerable.Range(0, names.Length).Select(index =>
        {
            int load = (tick * 7 + index * 3) % 11;
            return new
            {
                Server = names[index] + ".evotec.xyz",
                Queued = load * 4,
                Deferred = index == 2 ? 12 + tick * 5 : load % 3,
                Delivered = 1200 + tick * 85 + load * 9,
                Status = index == 2 && tick > 2 ? "Warn" : "Pass"
            };
        });
        return Table.For(rows);
    },
    new WatchOptions
    {
        Title = "Mail queues",
        PollInterval = TimeSpan.FromSeconds(1.5),
        Count = 6,
        Differences = true
    });
Full program
using ConsoleMonster.Live;
using ConsoleMonster.Widgets;

// The same synthetic queue snapshots as watch.ps1; a real provider supplies these rows instead.
ConsoleWatch.Run(
    tick =>
    {
        string[] names = { "MX01", "MX02", "MX03", "MX04" };
        var rows = Enumerable.Range(0, names.Length).Select(index =>
        {
            int load = (tick * 7 + index * 3) % 11;
            return new
            {
                Server = names[index] + ".evotec.xyz",
                Queued = load * 4,
                Deferred = index == 2 ? 12 + tick * 5 : load % 3,
                Delivered = 1200 + tick * 85 + load * 9,
                Status = index == 2 && tick > 2 ? "Warn" : "Pass"
            };
        });
        return Table.For(rows);
    },
    new WatchOptions
    {
        Title = "Mail queues",
        PollInterval = TimeSpan.FromSeconds(1.5),
        Count = 6,
        Differences = true
    });

The recording ran the PowerShell script. This C# program does the same with the library and compiles as shown; its timings are its own.

C# fluentProgram.cs
// The same synthetic queue snapshots as watch.ps1; a real provider supplies these rows instead.
ConsoleWatch.Run(
    tick =>
    {
        string[] names = { "MX01", "MX02", "MX03", "MX04" };
        var rows = Enumerable.Range(0, names.Length).Select(index =>
        {
            int load = (tick * 7 + index * 3) % 11;
            return new
            {
                Server = names[index] + ".evotec.xyz",
                Queued = load * 4,
                Deferred = index == 2 ? 12 + tick * 5 : load % 3,
                Delivered = 1200 + tick * 85 + load * 9,
                Status = index == 2 && tick > 2 ? "Warn" : "Pass"
            };
        });
        return Ui.Table(rows);
    },
    new WatchOptions()
        .Title("Mail queues")
        .PollInterval(TimeSpan.FromSeconds(1.5))
        .Count(6)
        .Differences());
Full program
using ConsoleMonster.Live;
using ConsoleMonster.Widgets;
using ConsoleMonster;

// The same synthetic queue snapshots as watch.ps1; a real provider supplies these rows instead.
ConsoleWatch.Run(
    tick =>
    {
        string[] names = { "MX01", "MX02", "MX03", "MX04" };
        var rows = Enumerable.Range(0, names.Length).Select(index =>
        {
            int load = (tick * 7 + index * 3) % 11;
            return new
            {
                Server = names[index] + ".evotec.xyz",
                Queued = load * 4,
                Deferred = index == 2 ? 12 + tick * 5 : load % 3,
                Delivered = 1200 + tick * 85 + load * 9,
                Status = index == 2 && tick > 2 ? "Warn" : "Pass"
            };
        });
        return Ui.Table(rows);
    },
    new WatchOptions()
        .Title("Mail queues")
        .PollInterval(TimeSpan.FromSeconds(1.5))
        .Count(6)
        .Differences());

The recording ran the PowerShell script. This C# program does the same with the library and compiles as shown; its timings are its own.

Watch-Console runs the script block every -PollIntervalSeconds seconds and replaces the view with its latest output, shaped as Show-ConsoleTable shapes it. -Differences marks the cells that changed since the previous run, a run that fails shows its error and the watch goes on, and -Count ends it after that many runs. Ctrl+C ends it and leaves the last frame in the scrollback. Piped on, or without an interactive console, every run is printed instead.

Pester tests as they run

Invoke-ConsolePester takes Pester's parameters and shows the current test, a cell per test and each failure with its expected and actual values.

Invoke-ConsolePester 96×2424-bitFull
Install-Module ConsoleMonster -Scope CurrentUser
Install-Module Pester -Scope CurrentUser -SkipPublisherCheck
PowerShellpester.ps1View on GitHub
# Pester 5 tests with a live view: the current test, counts so far and the failures as they happen.
Invoke-ConsolePester -Path ./fixtures -Title 'Mail domain checks'
Full program
Import-Module ConsoleMonster

# Pester 5 tests with a live view: the current test, counts so far and the failures as they happen.
Invoke-ConsolePester -Path ./fixtures -Title 'Mail domain checks'
PowerShellfixtures/MailDomain.Tests.ps1
# Invented checks for the Pester demo: short waits stand in for DNS lookups.
Describe 'evotec.xyz' {
    Context 'MX' {
        It 'has two MX records' { Start-Sleep -Milliseconds 220; 2 | Should -Be 2 }
        It 'points at Exchange Online' {
            Start-Sleep -Milliseconds 180
            'evotec-xyz.mail.protection.outlook.com' | Should -BeLike '*.outlook.com'
        }
        It 'answers on port 25' { Start-Sleep -Milliseconds 260; $true | Should -BeTrue }
    }
    Context 'SPF' {
        It 'publishes one SPF record' { Start-Sleep -Milliseconds 150; 1 | Should -Be 1 }
        It 'stays under 10 DNS lookups' { Start-Sleep -Milliseconds 240; 9 | Should -BeLessThan 10 }
        It 'ends with -all' { Start-Sleep -Milliseconds 120; '-all' | Should -Be '-all' }
    }
    Context 'DMARC' {
        It 'publishes a DMARC record' {
            Start-Sleep -Milliseconds 200
            'v=DMARC1' | Should -Not -BeNullOrEmpty
        }
        It 'enforces a reject policy' {
            Start-Sleep -Milliseconds 230
            'none' | Should -Be 'reject'
        }
        It 'sends aggregate reports' {
            Start-Sleep -Milliseconds 140
            'mailto:[email protected]' | Should -Match '^mailto:'
        }
    }
    Context 'DKIM' {
        It 'signs with selector1' {
            Start-Sleep -Milliseconds 170
            'selector1' | Should -Be 'selector1'
        }
        It 'uses 2048-bit keys' {
            Start-Sleep -Milliseconds 210
            1024 | Should -BeGreaterOrEqual 2048
        }
        It 'rotates keys yearly' -Skip { }
    }
    Context 'MTA-STS' {
        It 'serves the policy file' { Start-Sleep -Milliseconds 250; 200 | Should -Be 200 }
        It 'is in enforce mode' { Start-Sleep -Milliseconds 160; 'enforce' | Should -Be 'enforce' }
    }
}

Run: pwsh ./pester.ps1 · with MailDomain.Tests.ps1 saved in a fixtures folder beside it

C#pester.host.csView on GitHub
// A compiled cmdlet: the current PowerShell runspace owns native commands and callbacks.
[Cmdlet(VerbsLifecycle.Invoke, "PesterExample") ]
public sealed class PesterExample : PSCmdlet {
    protected override void ProcessRecord() {
        using var runner = new ConsolePester(
            this,
            new ConsolePesterOptions
            {
                Path = new[] { "./fixtures" },
                Title = "Mail domain checks"
            });
        runner.Run();
    }
}
Full program
using System.Management.Automation;
using ConsoleMonster.PowerShell.Pester;

// A compiled cmdlet: the current PowerShell runspace owns native commands and callbacks.
[Cmdlet(VerbsLifecycle.Invoke, "PesterExample") ]
public sealed class PesterExample : PSCmdlet {
    protected override void ProcessRecord() {
        using var runner = new ConsolePester(
            this,
            new ConsolePesterOptions
            {
                Path = new[] { "./fixtures" },
                Title = "Mail domain checks"
            });
        runner.Run();
    }
}

Download HostExample.csproj beside the source file.

PowerShell 7
Import-Module ConsoleMonster
$moduleBinary = Split-Path (Get-Command Show-Console).DLL
dotnet build ./HostExample.csproj -c Release "-p:ConsoleMonsterModuleDirectory=$moduleBinary"
Import-Module ./bin/Release/net8.0/HostExample.dll
Invoke-PesterExample

This is a compiled PowerShell cmdlet class. Reference the installed module’s ConsoleMonster and ConsoleMonster.PowerShell assemblies in a PowerShell module project; ProcessRecord runs on the owning pipeline thread. Download the project beside the source file and build/run it from PowerShell 7.

C# fluentpester.host.cs
// A compiled cmdlet: the current PowerShell runspace owns native commands and callbacks.
[Cmdlet(VerbsLifecycle.Invoke, "PesterExample")]
public sealed class PesterExample : PSCmdlet
{
    protected override void ProcessRecord()
    {
        using var runner = new ConsolePester(
            this,
            new ConsolePesterOptions().Path(new[] { "./fixtures" }).Title("Mail domain checks"));
        runner.Run();
    }
}
Full program
using System.Management.Automation;
using ConsoleMonster.PowerShell.Pester;

// A compiled cmdlet: the current PowerShell runspace owns native commands and callbacks.
[Cmdlet(VerbsLifecycle.Invoke, "PesterExample")]
public sealed class PesterExample : PSCmdlet
{
    protected override void ProcessRecord()
    {
        using var runner = new ConsolePester(
            this,
            new ConsolePesterOptions().Path(new[] { "./fixtures" }).Title("Mail domain checks"));
        runner.Run();
    }
}

Download HostExample.csproj beside the source file.

PowerShell 7
Import-Module ConsoleMonster
$moduleBinary = Split-Path (Get-Command Show-Console).DLL
dotnet build ./HostExample.csproj -c Release "-p:ConsoleMonsterModuleDirectory=$moduleBinary"
Import-Module ./bin/Release/net8.0/HostExample.dll
Invoke-PesterExample

This is a compiled PowerShell cmdlet class. Reference the installed module’s ConsoleMonster and ConsoleMonster.PowerShell assemblies in a PowerShell module project; ProcessRecord runs on the owning pipeline thread. Download the project beside the source file and build/run it from PowerShell 7.

Invoke-ConsolePester takes Pester's own parameters (-Path, -TagFilter, -Configuration...) and shows the run as it happens: a file list with progress, one cell per test, the test running now and each failure with its expected and actual values. It returns Pester's result object with -PassThru. When the run ends, a table of results by file, the failures and the totals are written; in redirected output and CI they are plain text.

Next

  • Large runs: monitor work your script already schedules, with finished items in scrollback.
  • Threads and concurrency: runspaces, parallel workers and what is safe from which thread.
  • Live sessions: build a view of your own around running work.

Edit this page on GitHub