Skip to content
ConsoleMonster

Recording and replay

Record a whole terminal session, including native commands, to asciicast v2 and export an HTML player, animated SVG, text, Markdown or a final frame.

Record a terminal session with native commands, colours and chapter markers, then share it as a local HTML player or asciicast v2 file.

Try it

This example records a real Git command and coloured PowerShell output, then writes command-review.cast and a self-contained command-review.html player. Use a terminal with Git installed and an empty output folder. The C# version starts PowerShell 7, so pwsh must be on your PATH.

Install-Module ConsoleMonster -Scope CurrentUser
PowerShellrecord-command.ps1
Import-Module ConsoleMonster

$recording = @{
    Path = './command-review.html'
    Title = 'Command review'
    Width = 88
    Height = 10
}

Invoke-ConsoleRecording {
    Add-ConsoleRecordingMarker 'Inspect'
    git --version

    Add-ConsoleRecordingMarker 'Report'
    Write-Host 'Review complete' -ForegroundColor Green
} @recording

Run: ./record-command.ps1

Terminal
dotnet new console -n CommandRecording
cd CommandRecording
dotnet add package ConsoleMonster
C#Program.cs
using ConsoleMonster.Export;
using ConsoleMonster.Sessions;

var options = new SessionRecordingOptions
{
    RecordingPath = "command-review.cast",
    Shell = "pwsh",
    Width = 88,
    Height = 10
};
options.Arguments.Add("-NoLogo");
options.Arguments.Add("-NoProfile");
options.Arguments.Add("-Command");
options.Arguments.Add("git --version; Write-Host 'Review complete' -ForegroundColor Green");
using (var recorder = SessionRecorder.Start(options, Console.Write))
{
    recorder.AddMarker("Inspect");
    recorder.WaitForExit();
}

var recording = SessionRecording.Read(options.RecordingPath);
var export = new RecordingExportOptions
{
    WindowChrome = true,
    Title = "Command review"
};
File.WriteAllText("command-review.html", recording.Render(OutputFormat.Html, export).ToText());

Run: dotnet run

Terminal
dotnet new console -n CommandRecording
cd CommandRecording
dotnet add package ConsoleMonster
C# fluentProgram.cs
var options = new SessionRecordingOptions()
    .RecordingPath("command-review.cast")
    .Shell("pwsh")
    .Width(88)
    .Height(10);
options.Arguments.Add("-NoLogo");
options.Arguments.Add("-NoProfile");
options.Arguments.Add("-Command");
options.Arguments.Add("git --version; Write-Host 'Review complete' -ForegroundColor Green");
using (var recorder = SessionRecorder.Start(options, Console.Write))
{
    recorder.AddMarker("Inspect");
    recorder.WaitForExit();
}

var recording = SessionRecording.Read(options.RecordingPath!);
var export = new RecordingExportOptions().WindowChrome().Title("Command review");
File.WriteAllText("command-review.html", recording.Render(OutputFormat.Html, export).ToText());
Full program
using ConsoleMonster.Export;
using ConsoleMonster.Sessions;

var options = new SessionRecordingOptions()
    .RecordingPath("command-review.cast")
    .Shell("pwsh")
    .Width(88)
    .Height(10);
options.Arguments.Add("-NoLogo");
options.Arguments.Add("-NoProfile");
options.Arguments.Add("-Command");
options.Arguments.Add("git --version; Write-Host 'Review complete' -ForegroundColor Green");
using (var recorder = SessionRecorder.Start(options, Console.Write))
{
    recorder.AddMarker("Inspect");
    recorder.WaitForExit();
}

var recording = SessionRecording.Read(options.RecordingPath!);
var export = new RecordingExportOptions().WindowChrome().Title("Command review");
File.WriteAllText("command-review.html", recording.Render(OutputFormat.Html, export).ToText());

Run: dotnet run

Command review Native outputasciicast v2

Open command-review.html in a browser. The cast and its .cast.json metadata stay beside it; nothing is uploaded. A new run needs a fresh destination because the recorder never overwrites an existing cast.

How it works

Invoke-ConsoleRecording starts an isolated PowerShell child inside a pseudo-console. Native commands and ConsoleMonster output reach the same terminal stream, including colour, cursor movement and progress redraws. Caller variables and functions are not inherited; keep required setup inside the script block.

These are the recording calls in the example:

Invoke-ConsoleRecording {
    Add-ConsoleRecordingMarker 'Inspect'
    git --version
    Add-ConsoleRecordingMarker 'Report'
    Write-Host 'Review complete' -ForegroundColor Green
} @recording

-Path selects the export and saves the original cast alongside it. Markers become named chapters in the HTML player. Its chapter menu and on-track ticks seek to a chapter; hover or focus a tick to see its name. ? opens keyboard help for Space, the arrow keys and number-key chapter shortcuts.

In C#, SessionRecorder.Start owns the child, AddMarker adds a chapter, and WaitForExit drains output and finalizes the cast. SessionRecording.Read loads it for export. SendInput forwards input without storing it; Resize records terminal size changes. Stop or disposal stops that recorder's child.

Windows uses ConPTY and needs Windows 10 version 1809 or later. Linux and macOS use openpty with a controlling terminal. The library targets .NET Standard 2.0, .NET Framework 4.7.2, .NET 8 and .NET 10, and the example's recorder API is the same on every target.

On macOS, each launch extracts a small embedded terminal helper into a private temporary directory and removes it after startup. Hosts that prohibit executing files from temporary directories reject recording startup with an operating-system permission error. Such hosts need a temporary directory where execution is permitted by their policy.

Variations

Watch a session with typed commands

This longer, real Invoke-ConsoleRecording capture inspects a synthetic Git repository, builds with live progress, then shows a ConsoleMonster table, a failing command and a redacted token. Its Inspect, Build and Report chapters jump to each part. Before playback, the poster shows the completed report.

Console session 100 columnsNative outputasciicast v2

Run: pwsh ./record-session.ps1 -OutputDirectory ./session-demo

The recording script uses Show-ConsolePresentation with a plain PowerShell demo. It types commands into one real child terminal and detects readiness through OSC 133 marks, so the visible prompt can change on any operating system. The synthetic repository lives under the output folder. The script explicitly redacts its synthetic token to API_TOKEN=[REDACTED] (synthetic) before the cast is written. See Talks and demos for directives, presenter controls and slide exports.

Download the HTML player, animated SVG, asciicast v2, text, Markdown or final frame. To reproduce the typed session, save both source files together in an empty folder.

Record an interactive terminal

Start a recording in your terminal, enter commands in the child, then stop it:

Invoke-ConsoleRecording -Interactive -RecordingPath ./interactive.cast -Title 'Deployment'
git --version
Add-ConsoleRecordingMarker 'Deploy'
Stop-ConsoleRecording

Exiting the child also finalizes the cast and returns to the original terminal. PowerShell children load the recording commands automatically; for cmd or a Unix shell, type exit. -Shell chooses the executable. The PowerShell cmdlets default to the current PowerShell executable. The ● REC indicator is in the window title and is not recorded.

Without -Path, filenames use the date, time and a unique suffix under Documents/ConsoleMonster/Recordings. Use -Folder to choose another location.

Export the same cast in another format

Export-ConsoleRecording -RecordingPath ./command-review.cast -Path ./command-review.svg
Export-ConsoleRecording -RecordingPath ./command-review.cast -Path ./command-review.txt
Export-ConsoleRecording -RecordingPath ./command-review.cast -Path ./command-review.md
Export-ConsoleRecording -RecordingPath ./command-review.cast -Path ./command-review-final.svg `
    -FinalFrame -Theme Light -ChromeStyle Windows

-Format PlayerData writes JSON for embedding the same player. -Theme Dark or Light uses the exporter's dark or light palette. Animated SVG uses CSS keyframes; the final-frame SVG is static. Text and Markdown include the main screen's scrollback. Whole-session casts remain asciicast v2, including output, marker and resize events. In C#, ExportFinalSvg writes a static frame and FinalFrame returns a CellBuffer for the exporter.

Redact values and bound a recording

Input bytes are forwarded but never stored. A password prompt that disables terminal echo therefore adds no password text to the cast. Built-in output patterns mask bearer tokens, common API-key prefixes and assignments such as password=, api_key= and client_secret=. Add regular expressions for your own values:

Invoke-ConsoleRecording {
    Write-Host 'account=sample-account'
    Write-Host 'api_key=synthetic-demo-value'
} -Path ./redacted.html -Redact 'sample-account' `
    -IdleLimitSeconds 2 -MaxBytes 10485760 -TimeoutSeconds 600

Resolving the default recording folder does not check Documents access. An explicit destination can record without touching that folder.

Redaction runs before the cast or chapter metadata is written, and also catches secrets split across reads or colour codes. When a pattern cannot be applied safely, the cast shows a visible omission message instead of the raw text. Review a recording before sharing it because patterns cannot recognize every secret.

-RedactionText chooses a replacement such as seven bullets; the default is [REDACTED]. Match only the value when surrounding context should stay visible. Replacement text cannot contain control characters. In C#, set SessionRecordingOptions.RedactionText.

-IdleLimitSeconds compresses longer gaps; zero preserves timing. -MaxBytes caps the cast, including its header. At the cap, the cast stays valid and a warning appears; the child continues while further output is omitted. -TimeoutSeconds stops the child after the specified time.

Use the limited in-process fallback

When a host cannot create a pseudo-console, explicitly select -InProcess:

Invoke-ConsoleRecording {
    Add-ConsoleRecordingMarker 'Summary'
    Write-Host 'PowerShell output only'
} -InProcess -Path ./summary.html

It captures PowerShell host and pipeline output in an in-process runspace. The cast header and metadata say in-process output only, and the command prints a warning. Native terminal behaviour, cursor movement and resize handling need pseudo-console mode.

Choose a window style

Use -ChromeStyle MacOS, Windows or Linux on Export-ConsoleFrame, Export-ConsoleRecording and Invoke-ConsoleRecording. The same style applies to static HTML and SVG, the HTML player, animated SVG and a session's final frame. These are generic vector shapes; no operating-system assets or logos are used.

Each command below runs on its own after installing ConsoleMonster. It creates the panel shown above and saves an SVG in the current directory. Change -Theme Dark to Light for the light sample, or change .svg to .html for selectable HTML.

MacOS

Import-Module ConsoleMonster
New-ConsolePanel -Title 'Build' -Content { New-ConsoleText '8 of 8 checks passed' } |
    Export-ConsoleFrame -Path ./build-macos.svg -Width 36 -Theme Dark -Title 'Build report' -ChromeStyle MacOS

Windows

Import-Module ConsoleMonster
New-ConsolePanel -Title 'Build' -Content { New-ConsoleText '8 of 8 checks passed' } |
    Export-ConsoleFrame -Path ./build-windows.svg -Width 36 -Theme Dark -Title 'Build report' -ChromeStyle Windows

Linux

Import-Module ConsoleMonster
New-ConsolePanel -Title 'Build' -Content { New-ConsoleText '8 of 8 checks passed' } |
    Export-ConsoleFrame -Path ./build-linux.svg -Width 36 -Theme Dark -Title 'Build report' -ChromeStyle Linux

MacOS has a 28px bar and three coloured dots. Windows has a 32px tab bar, prompt glyph, plus sign and line controls. Linux has a 36px header, a bold title and a round close control. Titles truncate within the space reserved for them. The bar uses the theme's Surface background and the control glyphs use Muted; only the macOS dots keep their traffic-light colours.

-ChromeStyle MacOS, Windows or Linux adds the chosen frame; -ChromeStyle None hides it. Text, Markdown and asciicast contain terminal content, so chrome adds no characters to those formats.

Record and export a Windows-style player, then a Linux-style final frame from the same cast:

Import-Module ConsoleMonster
Invoke-ConsoleRecording {
    Add-ConsoleRecordingMarker 'Build'
    Write-Host '8 of 8 checks passed' -ForegroundColor Green
} -Path ./chrome-demo.html -ChromeStyle Windows -Theme Light

Export-ConsoleRecording -RecordingPath ./chrome-demo.cast -Path ./chrome-demo-final.svg `
    -FinalFrame -ChromeStyle Linux -Theme Light -Title 'Build report'

In C#, set ChromeStyle on the export options. WindowChromeStyle.None hides the frame:

using ConsoleMonster.Export;
using ConsoleMonster.Widgets;

var options = new ExportOptions {
    Width = 36, Theme = ExportTheme.Light, Title = "Build report",
    ChromeStyle = WindowChromeStyle.Windows
};
File.WriteAllText("build.svg", ConsoleExporter.ToSvg(TextBlock.Plain("8 of 8 checks passed"), options));

Make it readable

Pacing is applied when exporting, so the same cast can produce a quick preview and a readable presentation without another recording. After each burst of output, the settled screen is held long enough to read the new text. -Pace sets how long:

PaceUse it for
SlowSlides and talks, where people read along
NormalThe default; documentation and walkthroughs
FastQuick previews
SourceThe cast's own timing, with no reading holds

The preset changes the delays only: no screen is dropped and nothing is recorded again. Combine Source with -IdleLimitSeconds 0 to keep every source gap.

Export-ConsoleRecording ./run.cast -Path ./run.gif -Preset Slide16x9 -Pace Normal
Export-ConsoleRecording ./run.cast -Path ./run-slow.gif -Preset Slide16x9 -Pace Slow
# Keep the cast's source delays, with no reading holds or idle compression.
Export-ConsoleRecording ./run.cast -Path ./run-source.html -Pace Source -IdleLimitSeconds 0

-IdleLimitSeconds 2 caps source delays on an unchanged screen. It never shortens reading holds, explicit marker holds or the final hold (-HoldLastFrameSeconds 2). Source timestamps in new casts are preserved; the cast's idle_time_limit header is only a hint to other players. An older cast whose timestamps were already compressed cannot recover the lost pause.

Use -ChapterHoldSeconds 3 to freeze the screen at every chapter marker. Within any recorded script, add a hold without sleeping:

Write-Host 'Read these results'
Add-ConsoleRecordingMarker -HoldSeconds 3
# A labelled hold also starts a chapter.
Add-ConsoleRecordingMarker 'Results' -HoldSeconds 3

A hold freezes the screen as it was when the marker arrived, including when later output has the same timestamp. It adds time during export and does not wait during recording. Other asciicast players may ignore holds.

Trim with source positions, or with unique chapter labels. The start is included and the end is excluded. -TrimEndChapter Cleanup stops before that chapter and its hold. Earlier output is still replayed to reconstruct the screen at the new start.

Export-ConsoleRecording ./run.cast -Path ./results.gif -Preset Slide16x9 `
    -TrimStartChapter Install -TrimEndChapter Cleanup `
    -ChapterSpeeds @{ Install = 4; Results = 1 } -ChapterHoldSeconds 2
# Time boundaries use positions in the original cast, before speed and holds.
Export-ConsoleRecording ./run.cast -Path ./excerpt.svg -TrimStartSeconds 4 -TrimEndSeconds 18

Chapter speed multiplies -Speed for source and reading delays; explicit holds keep their requested duration. GIF, APNG, HTML/player data and animated SVG share this timeline. Raw session asciicast, text/transcripts and still PNG/SVG exports retain their source content and positions.

In C#, use RecordingExportOptions.Pace, IdleLimit, ChapterHold, TrimStart, TrimEnd, TrimStartChapter, TrimEndChapter and ChapterSpeeds. Durations are TimeSpan values. A running SessionRecorder accepts AddMarker(TimeSpan.FromSeconds(3)) or AddMarker(TimeSpan.FromSeconds(3), "Results"); SetPace(RecordingPace.Slow) records a pace instruction. From a recorded child, write SessionRecorder.MarkerSequence(TimeSpan.FromSeconds(3)) to its terminal output.

Record dashboard updates

A live dashboard can record the widget updates it applies instead of terminal bytes. Use Invoke-ConsoleDashboard -RecordingPath in PowerShell, or LiveSessionOptions.RecordingPath / RecordWriter in C#. Replay into the same dashboard with Show-ConsoleReplay -PlaybackMode Automatic, Show-ConsoleReplay or LiveSession.Replay. Dashboard recordings use JSON lines and export to asciicast v3; whole terminal sessions use asciicast v2.

Record, replay, export

One script: a dashboard defined once, a run recorded with -RecordingPath, the recording played back at twice the speed into the same dashboard, and a page with a player saved next to it.

record.ps1 100×1824-bitFull
Install-Module ConsoleMonster -Scope CurrentUser
PowerShellrecord.ps1View on GitHub
# Record a run, replay it and save it as a page. The dashboard is defined once: the run and the replay
# both draw into its widgets by name.
$dashboardParameters = @{
    Title = '[bold]Deploy[/]'
    Subtitle = 'web farm · 4 servers'
}
$dashboard = New-ConsoleDashboard @dashboardParameters -Content {
    New-ConsoleStatusList -Layout Strip -WidgetId phases -Content { 'Stage', 'Swap', 'Verify' }
    New-ConsolePanel -Title 'Servers' -Content {
        New-ConsoleStatusList -WidgetId servers -Content { 'web01', 'web02', 'web03', 'web04' }
    }
    New-ConsolePanel -Title 'Log' -Fill -Content { New-ConsoleLogRegion }
}
$recording = Join-Path ([IO.Path]::GetTempPath()) 'deploy.jsonl'

# 1. Run it, writing every update to the recording.
Invoke-ConsoleDashboard $dashboard -RecordingPath $recording {
    foreach ($phase in 'Stage', 'Swap', 'Verify') {
        Update-Console -Key $phase -Status Running -WidgetId 'phases'
        foreach ($server in 'web01', 'web02', 'web03', 'web04') {
            Update-Console -WidgetId servers -Key $server -Status Running -Detail $phase
            Wait-ConsoleDashboard -Seconds 0.25
            Update-Console -WidgetId servers -Key $server -Status Pass -Detail $phase
        }
        Write-ConsoleLogEntry "$phase done on 4 servers"
        Update-Console -Key $phase -Status Pass -WidgetId 'phases'
    }
}

# 2. Play it back at twice the speed, into the same dashboard.
Show-ConsoleReplay -PlaybackMode Automatic $dashboard $recording -Speed 2

# 3. Save it as a page with a player.
$recordingParameters = @{
    Format = 'Html'
    Path = (Join-Path ([IO.Path]::GetTempPath()) 'deploy.html')
    Width = 100
    Height = 16
}
$null = Export-ConsoleRecording $dashboard $recording @recordingParameters
Full program
Import-Module ConsoleMonster

# Record a run, replay it and save it as a page. The dashboard is defined once: the run and the replay
# both draw into its widgets by name.
$dashboardParameters = @{
    Title = '[bold]Deploy[/]'
    Subtitle = 'web farm · 4 servers'
}
$dashboard = New-ConsoleDashboard @dashboardParameters -Content {
    New-ConsoleStatusList -Layout Strip -WidgetId phases -Content { 'Stage', 'Swap', 'Verify' }
    New-ConsolePanel -Title 'Servers' -Content {
        New-ConsoleStatusList -WidgetId servers -Content { 'web01', 'web02', 'web03', 'web04' }
    }
    New-ConsolePanel -Title 'Log' -Fill -Content { New-ConsoleLogRegion }
}
$recording = Join-Path ([IO.Path]::GetTempPath()) 'deploy.jsonl'

# 1. Run it, writing every update to the recording.
Invoke-ConsoleDashboard $dashboard -RecordingPath $recording {
    foreach ($phase in 'Stage', 'Swap', 'Verify') {
        Update-Console -Key $phase -Status Running -WidgetId 'phases'
        foreach ($server in 'web01', 'web02', 'web03', 'web04') {
            Update-Console -WidgetId servers -Key $server -Status Running -Detail $phase
            Wait-ConsoleDashboard -Seconds 0.25
            Update-Console -WidgetId servers -Key $server -Status Pass -Detail $phase
        }
        Write-ConsoleLogEntry "$phase done on 4 servers"
        Update-Console -Key $phase -Status Pass -WidgetId 'phases'
    }
}

# 2. Play it back at twice the speed, into the same dashboard.
Show-ConsoleReplay -PlaybackMode Automatic $dashboard $recording -Speed 2

# 3. Save it as a page with a player.
$recordingParameters = @{
    Format = 'Html'
    Path = (Join-Path ([IO.Path]::GetTempPath()) 'deploy.html')
    Width = 100
    Height = 16
}
$null = Export-ConsoleRecording $dashboard $recording @recordingParameters

Run: . ./record.ps1

Terminal
dotnet new console -n Record
cd Record
dotnet add package ConsoleMonster
C#Program.csView on GitHub
// Record a run, replay it and save it as a page. The dashboard is defined once: the run and the replay both draw
// into its widgets by name.
string[] servers = { "web01", "web02", "web03", "web04" };
Phases phases = new Phases().Set("Stage").Set("Swap").Set("Verify");
StatusList list = new StatusList("servers");
foreach (string server in servers)
{
    list.Set(server, server, StatusKind.Pending);
}

Dashboard dashboard = Ui.Dashboard().Title("[bold]Deploy[/]")
    .Subtitle("web farm · 4 servers")
    .Content(body => body
        .Add(phases)
        .Panel(new Panel(list, "Servers"))
        .Add(new Panel(new LogRegion(), "Log").Fill()));
string recording = Path.Combine(Path.GetTempPath(), "deploy.jsonl");

// 1. Run it, writing every update to the recording.
using (LiveSession session = new LiveSession(
    dashboard,
    new LiveSessionOptions { RecordingPath = recording }))
{
    session.Run(s =>
    {
        PhasesHandle phase = phases.Handle(s);
        StatusListHandle status = list.Handle(s);
        foreach (string step in new[] { "Stage", "Swap", "Verify" }

        )
        {
            phase.Start(step);
            foreach (string server in servers)
            {
                status.Set(server, StatusKind.Running);
                status.Detail(server, step);
                s.Delay(TimeSpan.FromMilliseconds(250));
                status.Set(server, StatusKind.Pass);
            }

            s.Post(new LiveEvent("log", "write", default, step + " done on 4 servers", "info"));
            phase.Complete(step, StatusKind.Pass);
        }
    });
}

// 2. Play it back at twice the speed, into the same dashboard.
using (StreamReader reader = File.OpenText(recording))
{
    LiveSession.Replay(dashboard, reader, new LiveSessionOptions(), 2);
}

// 3. Save it as a page with a player.
using (StreamReader reader = File.OpenText(recording))
{
    File.WriteAllText(
        Path.Combine(Path.GetTempPath(), "deploy.html"),
        Recording.ToHtml(
            dashboard,
            reader,
            new RecordingExportOptions { Width = 100, Height = 16 }));
}
Full program
using ConsoleMonster;
using ConsoleMonster.Layout;
using ConsoleMonster.Export;
using ConsoleMonster.Live;
using ConsoleMonster.Styling;
using ConsoleMonster.Widgets;

// Record a run, replay it and save it as a page. The dashboard is defined once: the run and the replay both draw
// into its widgets by name.
string[] servers = { "web01", "web02", "web03", "web04" };
Phases phases = new Phases().Set("Stage").Set("Swap").Set("Verify");
StatusList list = new StatusList("servers");
foreach (string server in servers)
{
    list.Set(server, server, StatusKind.Pending);
}

Dashboard dashboard = Ui.Dashboard().Title("[bold]Deploy[/]")
    .Subtitle("web farm · 4 servers")
    .Content(body => body
        .Add(phases)
        .Panel(new Panel(list, "Servers"))
        .Add(new Panel(new LogRegion(), "Log").Fill()));
string recording = Path.Combine(Path.GetTempPath(), "deploy.jsonl");

// 1. Run it, writing every update to the recording.
using (LiveSession session = new LiveSession(
    dashboard,
    new LiveSessionOptions { RecordingPath = recording }))
{
    session.Run(s =>
    {
        PhasesHandle phase = phases.Handle(s);
        StatusListHandle status = list.Handle(s);
        foreach (string step in new[] { "Stage", "Swap", "Verify" }

        )
        {
            phase.Start(step);
            foreach (string server in servers)
            {
                status.Set(server, StatusKind.Running);
                status.Detail(server, step);
                s.Delay(TimeSpan.FromMilliseconds(250));
                status.Set(server, StatusKind.Pass);
            }

            s.Post(new LiveEvent("log", "write", default, step + " done on 4 servers", "info"));
            phase.Complete(step, StatusKind.Pass);
        }
    });
}

// 2. Play it back at twice the speed, into the same dashboard.
using (StreamReader reader = File.OpenText(recording))
{
    LiveSession.Replay(dashboard, reader, new LiveSessionOptions(), 2);
}

// 3. Save it as a page with a player.
using (StreamReader reader = File.OpenText(recording))
{
    File.WriteAllText(
        Path.Combine(Path.GetTempPath(), "deploy.html"),
        Recording.ToHtml(
            dashboard,
            reader,
            new RecordingExportOptions { Width = 100, Height = 16 }));
}

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 Record
cd Record
dotnet add package ConsoleMonster
C# fluentProgram.cs
// Record a run, replay it and save it as a page. The dashboard is defined once: the run and the replay both draw
// into its widgets by name.
string[] servers = { "web01", "web02", "web03", "web04" };
Phases phases = Ui.Phases().Set("Stage").Set("Swap").Set("Verify");
StatusList list = Ui.StatusList("servers");
foreach (string server in servers)
{
    list.Set(server, server, StatusKind.Pending);
}

Dashboard dashboard = Ui.Dashboard()
    .Title("[bold]Deploy[/]")
    .Subtitle("web farm · 4 servers")
    .Content(body => body.Add(phases).Panel(Ui.Panel().Title("Servers").Content(panelContent =>
    {
        panelContent.Add(list);
    })).Add(Ui.Panel().Title("Log").Content(panelContent =>
    {
        panelContent.LogRegion();
    }).Fill()));
string recording = Path.Combine(Path.GetTempPath(), "deploy.jsonl");

// 1. Run it, writing every update to the recording.
using (LiveSession session = dashboard.CreateSession(options =>
{
    options.RecordingPath(recording);
}))
{
    session.Run(s =>
    {
        PhasesHandle phase = phases.Handle(s);
        StatusListHandle status = list.Handle(s);
        foreach (string step in new[] { "Stage", "Swap", "Verify" }

        )
        {
            phase.Start(step);
            foreach (string server in servers)
            {
                status.Set(server, StatusKind.Running);
                status.Detail(server, step);
                s.Delay(TimeSpan.FromMilliseconds(250));
                status.Set(server, StatusKind.Pass);
            }

            s.Post(new LiveEvent("log", "write", default, step + " done on 4 servers", "info"));
            phase.Complete(step, StatusKind.Pass);
        }
    });
}

// 2. Play it back at twice the speed, into the same dashboard.
using (StreamReader reader = File.OpenText(recording))
{
    LiveSession.Replay(dashboard, reader, new LiveSessionOptions(), 2);
}

// 3. Save it as a page with a player.
using (StreamReader reader = File.OpenText(recording))
{
    File.WriteAllText(
        Path.Combine(Path.GetTempPath(), "deploy.html"),
        Recording.ToHtml(dashboard, reader, new RecordingExportOptions().Width(100).Height(16)));
}
Full program
using ConsoleMonster;
using ConsoleMonster.Layout;
using ConsoleMonster.Export;
using ConsoleMonster.Live;
using ConsoleMonster.Styling;
using ConsoleMonster.Widgets;

// Record a run, replay it and save it as a page. The dashboard is defined once: the run and the replay both draw
// into its widgets by name.
string[] servers = { "web01", "web02", "web03", "web04" };
Phases phases = Ui.Phases().Set("Stage").Set("Swap").Set("Verify");
StatusList list = Ui.StatusList("servers");
foreach (string server in servers)
{
    list.Set(server, server, StatusKind.Pending);
}

Dashboard dashboard = Ui.Dashboard()
    .Title("[bold]Deploy[/]")
    .Subtitle("web farm · 4 servers")
    .Content(body => body.Add(phases).Panel(Ui.Panel().Title("Servers").Content(panelContent =>
    {
        panelContent.Add(list);
    })).Add(Ui.Panel().Title("Log").Content(panelContent =>
    {
        panelContent.LogRegion();
    }).Fill()));
string recording = Path.Combine(Path.GetTempPath(), "deploy.jsonl");

// 1. Run it, writing every update to the recording.
using (LiveSession session = dashboard.CreateSession(options =>
{
    options.RecordingPath(recording);
}))
{
    session.Run(s =>
    {
        PhasesHandle phase = phases.Handle(s);
        StatusListHandle status = list.Handle(s);
        foreach (string step in new[] { "Stage", "Swap", "Verify" }

        )
        {
            phase.Start(step);
            foreach (string server in servers)
            {
                status.Set(server, StatusKind.Running);
                status.Detail(server, step);
                s.Delay(TimeSpan.FromMilliseconds(250));
                status.Set(server, StatusKind.Pass);
            }

            s.Post(new LiveEvent("log", "write", default, step + " done on 4 servers", "info"));
            phase.Complete(step, StatusKind.Pass);
        }
    });
}

// 2. Play it back at twice the speed, into the same dashboard.
using (StreamReader reader = File.OpenText(recording))
{
    LiveSession.Replay(dashboard, reader, new LiveSessionOptions(), 2);
}

// 3. Save it as a page with a player.
using (StreamReader reader = File.OpenText(recording))
{
    File.WriteAllText(
        Path.Combine(Path.GetTempPath(), "deploy.html"),
        Recording.ToHtml(dashboard, reader, new RecordingExportOptions().Width(100).Height(16)));
}

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.

After the run

  1. The script is dot-sourced, so $dashboard stays defined. The recording and a page with a player are in your temporary folder; open the page to scrub through the run.

    PowerShell
    Invoke-Item (Join-Path ([IO.Path]::GetTempPath()) 'deploy.html')
  2. To rewind it in the terminal instead, with markers, failures and log search, use Show-ConsoleReplay.

    PowerShell
    Show-ConsoleReplay $dashboard (Join-Path ([IO.Path]::GetTempPath()) 'deploy.jsonl')

See also: Invoke-ConsoleDashboard, Export-ConsoleRecording

Automate a terminal capture in C#

SessionRecorder can wait for child output before sending input. This example needs PowerShell 7 on PATH:

using ConsoleMonster.Sessions;

var options = new SessionRecordingOptions {
    Shell = "pwsh",
    Arguments = { "-NoLogo", "-NoProfile", "-Command", "[Console]::WriteLine('READY'); [Console]::WriteLine([Console]::ReadLine())" },
    RecordingPath = "scripted.cast",
    Width = 80,
    Height = 20,
    Timeout = TimeSpan.FromSeconds(30),
    SessionTimeout = TimeSpan.FromSeconds(30),
    RespondToCursorQueries = true
};
using SessionRecorder recorder = SessionRecorder.Start(options);
recorder.WaitForOutput("READY", TimeSpan.FromSeconds(10));
recorder.SendInputAfter(TimeSpan.FromMilliseconds(50), "hello\r");
recorder.WaitForExit();

Timeout bounds the exit wait. SessionTimeout also bounds readiness and scripted-input work from startup. Cancellation and deadlines stop the owned child and drain its recording, including when the child stops reading input. WaitForExitWithInterrupt sends Ctrl+C at a chosen time from startup for a long-running child.

Enable RespondToCursorQueries for unattended Unix captures: the recorder answers cursor-position requests from its VT screen. Leave it off when forwarding output to a real terminal that supplies its own replies. Windows uses ConPTY's native console handling.

C# hosts can use SessionRecordingOptions.InProcess with SessionRecorder.CaptureOutput to record VT they emit themselves. This records output before a terminal can combine repaints; it does not intercept Console writes or capture input. CapturePowerShellOutput remains available for existing PowerShell host adapters.

All parameters are in the Invoke-ConsoleRecording and Export-ConsoleRecording references.

Next

Edit this page on GitHub