Skip to content
ConsoleMonster

Product module views

One generic console view for every type a compiled PowerShell module returns: tables or cards chosen from the records, row limits, units and sentinels.

New in 3.1.2.

One view for every type a product module returns

An invented inventory module registers one generic view for its namespaces. Sixty processes become a table whose shared computer name moves into the header and which stops at 50 rows; a wide certificate template becomes a card that counts its empty fields; computers that never logged on say never.

Contoso.Inventory 130×17524-bitFull
PowerShellgeneric-views.ps1View on GitHub
Import-Module ./Contoso.Inventory
Enable-ConsoleFormatting

# 60 processes on one computer: its name moves into the header, and the table stops at 50 rows
Get-InventoryProcess -Count 60

# One wide record is a card: the fields that have a value, and a count of the empty ones
Get-InventoryTemplate

# Computers that never logged on say so, instead of a date in year 1
Get-InventoryComputer
Full program
Import-Module ConsoleMonster
Import-Module ./Contoso.Inventory
Enable-ConsoleFormatting

# 60 processes on one computer: its name moves into the header, and the table stops at 50 rows
Get-InventoryProcess -Count 60

# One wide record is a card: the fields that have a value, and a count of the empty ones
Get-InventoryTemplate

# Computers that never logged on say so, instead of a date in year 1
Get-InventoryComputer
PowerShellContoso.Inventory/Contoso.Inventory.psm1
# An invented product module: typed results in the Contoso.Inventory namespaces and one generic console view for all of
# them. A real product compiles Contoso.Inventory.cs into its own assembly and ships ConsoleMonster.PowerShell.Display
# beside it; this sample compiles it on import, against the display assembly the ConsoleMonster module loaded.
$core = [ConsoleMonster.Terminal].Assembly
$displayPath = Join-Path (Split-Path $core.Location) 'ConsoleMonster.PowerShell.Display.dll'
$display = if ($PSEdition -eq 'Core') {
    [System.Runtime.Loader.AssemblyLoadContext]::GetLoadContext($core).LoadFromAssemblyPath($displayPath)
} else {
    [Reflection.Assembly]::LoadFrom($displayPath)
}
$references = @($core.Location, $display.Location,
    [System.Management.Automation.PSObject].Assembly.Location)
$compile = @{}
if ($PSEdition -eq 'Core') {
    $references += @(Get-ChildItem (Join-Path $PSHOME 'ref') -Filter *.dll | ForEach-Object {
        $_.FullName
    })
    $compile.CompilerOptions = '/nowarn:1701'
} else {
    $references += 'System.Core'
}
$assemblyPath = Join-Path ([IO.Path]::GetTempPath()) ([guid]::NewGuid().ToString('N') + '.dll')
try {
    $source = Join-Path $PSScriptRoot 'Contoso.Inventory.cs'
    Add-Type -Path $source -ReferencedAssemblies $references -OutputAssembly $assemblyPath @compile
    $bytes = [IO.File]::ReadAllBytes($assemblyPath)
    # The product types must see the same display assembly as ConsoleMonster.
    $assembly = if ($PSEdition -eq 'Core') {
        $stream = [IO.MemoryStream]::new($bytes)
        try {
            [System.Runtime.Loader.AssemblyLoadContext]::GetLoadContext($core).LoadFromStream($stream)
        } finally { $stream.Dispose() }
    } else {
        [Reflection.Assembly]::Load($bytes)
    }
} finally {
    if (Test-Path -LiteralPath $assemblyPath) { Remove-Item -LiteralPath $assemblyPath }
}
$script:Samples = $assembly.GetType('Contoso.Inventory.Samples', $true)
$script:Lease = $assembly.GetType('Contoso.Inventory.Views', $true)::Register()
$ExecutionContext.SessionState.Module.OnRemove = { $script:Lease.Dispose() }

function Get-InventoryProcess {
    param([int] $Count = 12)
    $script:Samples::Processes($Count)
}

function Get-InventoryTemplate {
    param([string] $Name = 'WebServer')
    $script:Samples::Template($Name)
}

function Get-InventoryComputer {
    $script:Samples::Computers()
}

Export-ModuleMember -Function Get-InventoryProcess, Get-InventoryTemplate, Get-InventoryComputer
PowerShellContoso.Inventory/Contoso.Inventory.cs
using System;
using System.Collections.Generic;
using ConsoleMonster.PowerShell.Display;

// An invented inventory product: long process lists, a wide certificate template with many empty fields, computers
// that never logged on and nested identities. Every record is made up in memory; nothing is queried.
namespace Contoso.Inventory.Directory {
    public sealed class IdentityInfo {
        public string Name { get; set; }
        public string Sid { get; set; }
        public string Domain { get; set; }
        public string Kind { get; set; }
    }

    public sealed class ComputerInfo {
        public string Name { get; set; }
        public string SamAccountName { get; set; }
        public string DomainName { get; set; }
        public bool Enabled { get; set; }
        public string OperatingSystem { get; set; }
        public int LastLogonDays { get; set; }
        public DateTime LastLogon { get; set; }
        public DateTime PasswordLastSet { get; set; }
        public IdentityInfo ManagedBy { get; set; }
        public List<IdentityInfo> MemberOf { get; set; }
        public string Description { get; set; }
        public string Location { get; set; }
    }
}

namespace Contoso.Inventory.Processes {
    public sealed class ProcessInfo {
        public string ComputerName { get; set; }
        public int Id { get; set; }
        public string Name { get; set; }
        public string Path { get; set; }
        public string Owner { get; set; }
        public long MemoryUsage { get; set; }
        public TimeSpan CpuTime { get; set; }
        public int SessionId { get; set; }
        public DateTime? StartTimeUtc { get; set; }
        public string MainWindowTitle { get; set; }
        public bool HasMainWindow { get; set; }
        public bool IsResponding { get; set; }
    }
}

namespace Contoso.Inventory.Pki {
    public sealed class CertificateTemplate {
        public string Name { get; set; }
        public string DisplayName { get; set; }
        public string Oid { get; set; }
        public int SchemaVersion { get; set; }
        public int MinorRevision { get; set; }
        public string DistinguishedName { get; set; }
        public bool PublishedToActiveDirectory { get; set; }
        public bool AutoEnrollment { get; set; }
        public bool RequiresManagerApproval { get; set; }
        public bool EnrolleeSuppliesSubject { get; set; }
        public bool ExportableKey { get; set; }
        public int MinimumKeySize { get; set; }
        public TimeSpan ValidityPeriod { get; set; }
        public TimeSpan RenewalPeriod { get; set; }
        public List<string> ExtendedKeyUsage { get; set; }
        public List<string> ApplicationPolicies { get; set; }
        public List<string> IssuancePolicies { get; set; }
        public List<string> RaApplicationPolicies { get; set; }
        public int AuthorizedSignatures { get; set; }
        public string CryptoProvider { get; set; }
        public string KeyAlgorithm { get; set; }
        public string HashAlgorithm { get; set; }
        public string SubjectNameFormat { get; set; }
        public string SubjectAlternativeName { get; set; }
        public Directory.IdentityInfo Owner { get; set; }
        public List<Directory.IdentityInfo> EnrollmentRights { get; set; }
        public List<Directory.IdentityInfo> AutoEnrollmentRights { get; set; }
        public List<Directory.IdentityInfo> WriteRights { get; set; }
        public string SupersededTemplates { get; set; }
        public string PolicyServer { get; set; }
        public string Comment { get; set; }
        public string Category { get; set; }
        public string Purpose { get; set; }
        public string Notes { get; set; }
        public string ManagerContact { get; set; }
        public string ApprovalProcess { get; set; }
        public string ArchiveKey { get; set; }
        public string RecoveryAgent { get; set; }
        public string AttestationMode { get; set; }
        public string KeyUsage { get; set; }
        public string PrivateKeyFlags { get; set; }
        public string EnrollmentFlags { get; set; }
        public string CertificateNameFlags { get; set; }
        public string GeneralFlags { get; set; }
        public DateTime Created { get; set; }
        public DateTime Modified { get; set; }
        public int DaysSinceChange { get; set; }
        public Guid TemplateGuid { get; set; }
        public Guid ReplacementGuid { get; set; }
        public byte[] Thumbprint { get; set; }

        // A size matched by the view's *Bytes pattern that holds the "not reported" sentinel.
        public int ArchiveLimitBytes { get; set; }

        // A size the type declares itself, in kilobytes.
        [DefaultDisplayUnit(DefaultDisplayUnit.Kilobytes)]
        public long CacheSizeKb { get; set; }
    }
}

namespace Contoso.Inventory {
    /// <summary>Registers one generic console view for every Contoso.Inventory type.</summary>
    public static class Views {
        public static ModuleLease Register() {
            // Generic views need display feature level 5.
            ModuleLease lease = DefaultDisplay.RegisterModule(
                "Contoso.Inventory",
                new Version(1, 0),
                new string[0],
                5);
            DefaultDisplayGenericView view = lease.RegisterGenericView(
                "Contoso.Inventory.Generic",
                new Version(1, 0),
                new[] { "Contoso.Inventory" });

            // Sizes come from declared units, never from a guess at a member's name.
            view.Units["MemoryUsage"] = DefaultDisplayUnit.Bytes;
            view.Units["*Bytes"] = DefaultDisplayUnit.Bytes;
            return lease;
        }
    }

    /// <summary>Sample records shaped like the audit's worst cases.</summary>
    public static class Samples {
        private static readonly DateTime Now = new DateTime(2026, 10, 21, 9, 30, 0,
            DateTimeKind.Utc);

        public static Directory.IdentityInfo Identity(string name) {
            return new Directory.IdentityInfo
            {
                    Name = name,
                Sid = "S-1-5-21-1004336348-1177238915-682003330-" + (1100 + name.Length),
                Domain = "CONTOSO",
                Kind = "Group"
                };
        }

        public static List<Processes.ProcessInfo> Processes(int count) {
            string[] names = { "Idle", "System", "Registry", "smss", "csrss", "wininit", "services",
                "lsass", "svchost", "explorer", "pwsh", "code" };
            List<Processes.ProcessInfo> list = new List<Processes.ProcessInfo>();
            for (int i = 0; i < count; i++) {
                string name = names[i % names.Length];
                bool user = name == "explorer" || name == "pwsh" || name == "code";
                list.Add(new Processes.ProcessInfo
                {
                        ComputerName = "WS-0142",
                    Id = i == 0 ? 0 : 4 + i * 132,
                    Name = name,
                        Path = i < 2
                            ? null
                            : (user ? @"C:\Program Files\" : @"C:\Windows\System32\") + name
                                + ".exe",
                        Owner = user ? @"CONTOSO\alex" : null,
                    MemoryUsage = 8192L + i * 7340032L,
                    CpuTime = TimeSpan.FromSeconds(i * 37.5),
                        SessionId = user ? 1 : 0,
                    StartTimeUtc = i < 2 ? (DateTime?)null : Now.AddMinutes(-i * 41),
                        MainWindowTitle = user ? name + " window" : string.Empty,
                    HasMainWindow = user,
                    IsResponding = true
                    });
            }
            return list;
        }

        public static Pki.CertificateTemplate Template(string name) {
            return new Pki.CertificateTemplate
            {
                    Name = name,
                DisplayName = name + " (v2)",
                Oid = "1.3.6.1.4.1.311.21.8.4211781.10284337.4",
                SchemaVersion = 2,
                MinorRevision = 5,
                    DistinguishedName = "CN=" + name
                        + (",CN=Certificate Templates,CN=Public Key "
                            + "Services,CN=Services,CN=Configuration,DC=contoso,DC=com"),
                    PublishedToActiveDirectory = true,
                AutoEnrollment = true,
                ExportableKey = false,
                MinimumKeySize = 2048,
                    ValidityPeriod = TimeSpan.FromDays(365),
                RenewalPeriod = TimeSpan.FromDays(42),
                    ExtendedKeyUsage = new List<string> { "Client Authentication",
                        "Server Authentication", "Smart Card Logon", "Encrypting File System",
                        "Secure Email" },
                    ApplicationPolicies = new List<string>(),
                IssuancePolicies = new List<string>(),
                RaApplicationPolicies = new List<string>(),
                    CryptoProvider = "Microsoft Software Key Storage Provider",
                KeyAlgorithm = "RSA",
                HashAlgorithm = "SHA256",
                    SubjectNameFormat = "CommonName",
                Owner = Identity("Enterprise Admins"),
                    EnrollmentRights = new List<Directory.IdentityInfo>
                    {
                        Identity("Domain Computers"),
                        Identity("Domain Controllers"),
                        Identity("Workstation Admins")
                    },
                    AutoEnrollmentRights = new List<Directory.IdentityInfo>(),
                WriteRights = new List<Directory.IdentityInfo>(),
                    Created = Now.AddDays(-2369),
                Modified = Now.AddDays(-31),
                DaysSinceChange = 31,
                TemplateGuid = new Guid("5d2b5c55-1f9a-4c1b-bf3e-9a43a0c1d2e7"),
                    ReplacementGuid = Guid.Empty,
                ArchiveLimitBytes = int.MaxValue,
                CacheSizeKb = 2048,
                Thumbprint = new byte[] { 0xE7, 0xBA, 0xBC, 0x1B, 0x29, 0x3F, 0xD7, 0xA3, 0x10,
                    0x11, 0x3C, 0xA5, 0xEE, 0x05, 0x40, 0x04, 0xC7, 0xCE, 0x4A, 0x81 }
                };
        }

        public static List<Directory.ComputerInfo> Computers() {
            return new List<Directory.ComputerInfo> {
                Computer("DC01", true, "Windows Server 2022 Datacenter", 0, Now.AddHours(-3)),
                Computer("FS02", true, "Windows Server 2019 Standard", 9, Now.AddDays(-9)),
                Computer("AZUREADSSOACC", true, null, int.MaxValue, DateTime.MinValue),
                Computer("LEGACY-PC", false, "Windows 10 Pro", 1960, Now.AddDays(-1960)),
                Computer("KIOSK-07", false, null, int.MaxValue, DateTime.MinValue)
            };
        }

        private static Directory.ComputerInfo Computer(string name, bool enabled, string os,
            int days, DateTime logon) {
            return new Directory.ComputerInfo
            {
                    Name = name,
                SamAccountName = name + "$",
                DomainName = "contoso.com",
                Enabled = enabled,
                OperatingSystem = os,
                    LastLogonDays = days,
                LastLogon = logon,
                PasswordLastSet = logon == DateTime.MinValue
                    ? DateTime.MinValue
                    : logon.AddDays(-20),
                    ManagedBy = name.StartsWith("DC") ? Identity("Domain Admins") : null,
                    MemberOf = name.StartsWith("DC")
                        ? new List<Directory.IdentityInfo>
                        {
                            Identity("Domain Controllers"),
                            Identity("Pre-Windows 2000 Compatible Access"),
                            Identity("Denied RODC Password Replication Group"),
                            Identity("Cert Publishers")
                        }
                        : new List<Directory.IdentityInfo>()
                };
        }
    }
}

Give your module's types a view

PowerShell 5.1 and 7, with a compiled module
# In the module's import hook (C#), with ConsoleMonster.PowerShell.Display beside its binaries:
# ModuleLease lease = DefaultDisplay.RegisterModule("YourModule", version, ownedTypeNames, minimumFeatureLevel: 5);
# lease.RegisterGenericView("YourModule.Generic", new Version(1, 0), new[] { "YourModule" });
Import-Module YourModule
Import-Module ConsoleMonster
Enable-ConsoleFormatting

See also: Product module views

A compiled product module (an assessment toolkit with hundreds of commands, say) can give every result type a readable console view without writing one view per type. It references ConsoleMonster.PowerShell.Display, acquires a lease when it is imported and registers one generic view for its namespaces:

// In the module's import hook; dispose the lease from its removal hook.
ModuleLease lease = DefaultDisplay.RegisterModule("Contoso.Inventory", moduleVersion, ownedTypeNames, minimumFeatureLevel: 5);
DefaultDisplayGenericView view = lease.RegisterGenericView("Contoso.Inventory.Generic", new Version(1, 0), new[] { "Contoso.Inventory" });
view.SeverityMembers.Add("Severity");   // optional: rank capped records worst first

The namespace Contoso.Inventory covers Contoso.Inventory.Server and Contoso.Inventory.Reports.Summary. A type uses the generic view only when nothing else claims it: exact views, family views (IncludeDerivedTypes), user views (Register-ConsoleView) and PowerShell format data (.format.ps1xml) all take precedence. Set OverrideFormatData to replace format data, or Filter to keep particular types native. Collections, enums, delegates, exceptions and widgets are never covered, and product modules cannot register System, Microsoft, ConsoleMonster or Deserialized namespaces. The view follows the same host rules as other default views: only a real local console renders it, while redirection, remoting, transcripts, CI and explicit Format-* or Out-String stay native.

The generic view chooses its shape from the records:

  • One record, or up to 10 records whose fields would need more than about two screen widths, become cards: the record's name (Name, DisplayName, SamAccountName, ComputerName, HostName, DnsHostName, Title, Label, Key or Id) as the title, then each field that has a value, and a muted +N empty count.

  • More records become a table. The name column comes first and never hides; other columns rank by how often they are filled, whether their values differ and how long they are, so constant and sparse columns hide first when the window is narrow. A table keeps at most 12 columns and counts the rest below it.

  • Empty values are hidden: null, blank text, empty collections, an empty Guid and a None flag.

  • Booleans, dates (relative in tables, absolute and relative on cards), durations, identifiers and status words use the same presenters as other ConsoleMonster tables.

  • A table lifts text that is the same on every shown row (up to three columns, such as one computer name for every process) into its header line with the record count: WS-0142 · 300 processes. Cards keep every field.

  • Sizes and durations come from declared units, never from a guess at a name (MinimumKeySize is bits). Declare them on the view, by exact name or a * pattern, or on the member:

    view.Units["MemoryUsage"] = DefaultDisplayUnit.Bytes;
    view.Units["*Bytes"] = DefaultDisplayUnit.Bytes;
    view.Units["TimeoutMs"] = DefaultDisplayUnit.Milliseconds;
    
    [DefaultDisplayUnit(DefaultDisplayUnit.Kilobytes)] public long QuotaKb { get; set; }
    

    Bytes, kilobytes and megabytes show as KB, MB or GB; milliseconds and seconds as durations. A product can also use an attribute of its own named DisplayUnitAttribute whose first argument names the unit, without referencing this assembly.

  • Nested objects show their name member, or their own ToString() when the type overrides it, never the type name. Collections show their first three items and how many follow (Client Authentication, Server Authentication, Smart Card Logon … +2); byte arrays show as hex.

  • These values stand for "no value" and show as a muted word: DateTime and DateTimeOffset minimum and maximum, and TimeSpan minimum and maximum, are never; Int32, Int64, UInt32 and UInt64 minimum and maximum are never in members whose names end in Days or contain Logon or Login, and not reported elsewhere.

The view reads public fields and auto-properties through their storage, so it never runs a product getter that could query a directory or the network. Set ReadComputedProperties when every computed property of the covered types is cheap and has no side effects. A nested object without a name member shows through its own ToString() override, and collections are counted and previewed through ICollection, so keep those free of lookups too.

Row limits

Collected views stop at a row limit and end with a muted +N more line; in PowerShell it adds pipe to Format-Table for every row. A generic view shows 50 table rows or 10 cards. It holds at most that many records in the console, within the view's byte budget: without a severity member the first rows draw as soon as they arrive and later records are only counted, so thousands of results never wait in memory. Exports (Export-ConsoleFrame) collect their input first and show the same first rows. With a severity member it keeps the worst records seen so far and draws them worst first in the console (Critical and Fatal, then Error, Fail and High, then Warning and Medium, then the rest; numbers rank higher as worse).

An explicit Collect registration whose builder returns a Table also stops at 50 rows, with every record still passed to the builder so totals stay whole. Set RowLimit on a registration or generic view to change the limit, or 0 to show every record, and SeverityMember on a registration to order its records worst first. For one session, $ConsoleViewLengthPreference = 'Full' (or CONSOLEMONSTER_VIEW_LENGTH=Full for exports) shows every record.

Recordings and diagnostics

Invoke-ConsoleRecording runs each top-level statement of its script as its own submission, as if typed at the prompt, so a recording shows the same views as the console. A script with a param(), begin, process or dynamicparam clean block, a top-level trap or return, or class or enum definitions, runs as one submission instead; it still gets default views, but only from modules the recorded child has imported before the script starts. The child is a new PowerShell process that imports only ConsoleMonster, so a product module imported in the calling session is not there: import it in the recorded script, as its own statement. When a registered view stays native, set $VerbosePreference = 'Continue' to see why, once per reason: ConsoleMonster view 'Contoso.Inventory.Generic' used native formatting because output is redirected.

Module/Tests/Fixtures/GenericViews is a small sample product with processes, a wide certificate template, computers with never logons, nested identities and ranked findings.

Next

Edit this page on GitHub