An AI-driven stream of small, useful PowerShell experiments. Each lab starts with an idea, becomes a prompt, turns into a commented solution, and gets run in an isolated environment.
idea → prompt → solution → run
PowerShell 7 · sample data · proof
Stay connected
Follow along as the lab grows.
New experiments are added over time. Find Doug’s videos, projects, and builder community around the work.
From spark to proof
An idea comes in. A working lab comes out.
Each day, the lab looks for a small idea worth testing. AI reframes it as a prompt, generates the PowerShell, runs it safely, validates the output, and publishes the proof so you can copy the prompt and try it yourself.
After finding the scenario, AI turned it into this concise prompt. That prompt was then used to generate the PowerShell.
Create a safe PowerShell 7 plus Go/Wails desktop demo called Local Pulse Board. PowerShell should turn fictional service metrics into compact JSON, and the Wails Go core should accept that JSON and expose a formatted status summary to a small frontend. Keep the contract explicit, source-only, deterministic, and free of network, credentials, system changes, or compiled binaries.
2. The Runner AI Created
AI also created run.ps1. It prepares the sample data, passes the parameters, and invokes the generated PowerShell.
[CmdletBinding()]
param()
$ErrorActionPreference = 'Stop'
Set-StrictMode -Version Latest
$solutionPath = Join-Path $PSScriptRoot 'solution.ps1'
$metrics = @(
[pscustomobject]@{ Name = 'Search'; State = 'Ready'; LatencyMs = 42; QueueDepth = 3 }
[pscustomobject]@{ Name = 'Billing'; State = 'Watch'; LatencyMs = 118; QueueDepth = 9 }
[pscustomobject]@{ Name = 'Mail'; State = 'Ready'; LatencyMs = 57; QueueDepth = 1 }
)
$json = & $solutionPath -Metrics $metrics
Write-Output 'PowerShell JSON contract:'
Write-Output $json
if (Get-Command go -ErrorAction SilentlyContinue) {
Write-Output 'Go is available; the local Wails build can be attempted from wails-app.'
}
else {
Write-Output 'REVIEW-ONLY: Go/Wails is not installed in this cloud runtime; GUI execution was not attempted.'
}
3. The PowerShell AI Generated
solution.ps1 is the runnable PowerShell produced from the AI-created prompt.
# Convert fictional service metrics into the JSON contract consumed by the Go app.
[CmdletBinding()]
param(
# The caller supplies sample records so the function stays reusable and testable.
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[object[]] $Metrics
)
Set-StrictMode -Version Latest
# Project only the fields that form the stable PowerShell-to-Go boundary.
$payload = [pscustomobject]@{
GeneratedAt = '2026-09-22T07:00:00Z'
Services = @(
foreach ($metric in $Metrics) {
[pscustomobject]@{
Name = [string]$metric.Name
State = [string]$metric.State
LatencyMs = [int]$metric.LatencyMs
QueueDepth = [int]$metric.QueueDepth
}
}
)
}
# Emit compact, portable JSON for a file, stdin pipe, or Wails binding.
$payload | ConvertTo-Json -Depth 4 -Compress
4. What Happened When It Ran
The actual captured output, errors, and exit status.
PowerShell version: 7.6.6
Command: ./pwsh-runtime/pwsh -NoLogo -NoProfile -File run.ps1
=== STDOUT ===
PowerShell JSON contract:
{"GeneratedAt":"2026-09-22T07:00:00Z","Services":[{"Name":"Search","State":"Ready","LatencyMs":42,"QueueDepth":3},{"Name":"Billing","State":"Watch","LatencyMs":118,"QueueDepth":9},{"Name":"Mail","State":"Ready","LatencyMs":57,"QueueDepth":1}]}
REVIEW-ONLY: Go/Wails is not installed in this cloud runtime; GUI execution was not attempted.
=== STDERR ===
(empty)
=== EXIT STATUS ===
0
5. Validation Performed by the AI Workflow
The runtime, expected results, and safety boundaries were checked and recorded.
Validation StatusReview only
Runtime: PowerShell 7.6.6 Command: `./pwsh-runtime/pwsh -NoLogo -NoProfile -File run.ps1` Exit status: `0` Checks: JSON was generated from three in-memory metrics with the documented fields; the source bundle contains Go, frontend, build, and PowerShell files and no compiled executable. GUI check: Go and Wails were unavailable in the cloud runtime, so the desktop app was not run and no GUI result was fabricated. Safety: sample data only; no network, credentials, deletion, registry/system changes, or arbitrary code execution.
Lab · 2026-09-22
Incident Heatmap Workbook
Turn fictional incidents into a severity-by-team Excel heatmap.
Review only
AI found the scenario, created the prompt and runner, generated the PowerShell, ran it, and validated the result.
PowerShell 7 implementation
1. The Prompt AI Created for This Idea
After finding the scenario, AI turned it into this concise prompt. That prompt was then used to generate the PowerShell.
Using PowerShell 7 and ImportExcel, create a workbook from fictional incidents. Export a detail sheet and a team-by-severity summary with a color scale that acts as a heatmap. Use sample objects, a caller path, and no network, credentials, deletion, or system changes.
2. The Runner AI Created
AI also created run.ps1. It prepares the sample data, passes the parameters, and invokes the generated PowerShell.
solution.ps1 is the runnable PowerShell produced from the AI-created prompt.
# Export incident details and a severity heatmap with ImportExcel.
[CmdletBinding()]
param(
[Parameter(Mandatory)] [ValidateNotNullOrEmpty()] [object[]] $Incidents,
[Parameter(Mandatory)] [ValidateNotNullOrEmpty()] [string] $Path
)
Set-StrictMode -Version Latest
# Normalize each record so the workbook receives predictable columns.
$details = foreach ($incident in $Incidents) {
[pscustomobject]@{
Team = [string]$incident.Team
Severity = [string]$incident.Severity
Title = [string]$incident.Title
Minutes = [int]$incident.Minutes
}
}
# Build a stable matrix with one row per team and one column per severity.
$severities = 'Low','Medium','High','Critical'
$heatmap = foreach ($team in ($details.Team | Sort-Object -Unique)) {
$row = [ordered]@{ Team = $team }
foreach ($severity in $severities) {
$row[$severity] = @($details | Where-Object { $_.Team -eq $team -and $_.Severity -eq $severity }).Count
}
[pscustomobject]$row
}
$details | Export-Excel -Path $Path -WorksheetName 'Incidents' -TableName 'Incidents' -AutoSize -FreezeTopRow -BoldTopRow -ClearSheet
$heatmap | Export-Excel -Path $Path -WorksheetName 'Heatmap' -TableName 'SeverityHeatmap' -AutoSize -BoldTopRow -Append
# A three-color scale makes higher counts visually stand out during review.
$package = Open-ExcelPackage -Path $Path
$sheet = $package.Workbook.Worksheets['Heatmap']
Add-ConditionalFormatting -Worksheet $sheet -Address 'B2:E200' -RuleType ThreeColorScale -MinColor 'E2F0D9' -MidColor 'FFF2CC' -MaxColor 'F4CCCC' | Out-Null
Close-ExcelPackage $package
[pscustomobject]@{ Path = (Resolve-Path -LiteralPath $Path).Path; IncidentCount = $details.Count; TeamCount = $heatmap.Count }
4. What Happened When It Ran
The actual captured output, errors, and exit status.
PowerShell version: 7.6.6
Command: ./pwsh-runtime/pwsh -NoLogo -NoProfile -File run.ps1
=== STDOUT ===
(empty)
=== STDERR ===
Import-Module: run.ps1:5: The specified module 'ImportExcel' was not loaded because no valid module file was found in any module directory.
=== EXIT STATUS ===
1
5. Validation Performed by the AI Workflow
The runtime, expected results, and safety boundaries were checked and recorded.
Validation StatusReview only
Runtime: PowerShell 7.6.6 Command: `./pwsh-runtime/pwsh -NoLogo -NoProfile -File run.ps1` Exit status: `1` Module: ImportExcel was not installed or loadable in the cloud runtime, so workbook creation and version checks were not claimed. Checks: the script was reviewed for in-memory fictional records and bounded workbook formatting. Safety: no network, credentials, deletion, registry/system changes, or arbitrary code execution.
Lab · 2026-09-22
ASCII Dungeon Map
Generate a deterministic dungeon with rooms, corridors, and an exit marker.
Validated
AI found the scenario, created the prompt and runner, generated the PowerShell, ran it, and validated the result.
PowerShell 7 implementation
1. The Prompt AI Created for This Idea
After finding the scenario, AI turned it into this concise prompt. That prompt was then used to generate the PowerShell.
Create a fully commented PowerShell 7 function that prints a deterministic ASCII dungeon: bounded width and height, a few rectangular rooms joined by corridors, and an exit marker. Accept a seed, keep all state in memory, and emit plain text with no cursor control, network, or system changes.
2. The Runner AI Created
AI also created run.ps1. It prepares the sample data, passes the parameters, and invokes the generated PowerShell.
The runtime, expected results, and safety boundaries were checked and recorded.
Validation StatusPassed
Runtime: PowerShell 7.6.6 Command: `./pwsh-runtime/pwsh -NoLogo -NoProfile -File run.ps1` Exit status: `0` Checks: fixed seed produced a bounded 48 by 20 map containing rooms, corridors, `S`, and `E` markers. Safety: deterministic in-memory character generation only; no cursor control, network, credentials, deletion, or system changes.
Lab · 2026-09-22
Packing Grid Coordinate Planner
Place equal items into a bounded shelf grid with reusable coordinates.
Validated
AI found the scenario, created the prompt and runner, generated the PowerShell, ran it, and validated the result.
PowerShell 7 implementation
1. The Prompt AI Created for This Idea
After finding the scenario, AI turned it into this concise prompt. That prompt was then used to generate the PowerShell.
Create a fully commented PowerShell 7 function that places equal rectangular items into a shelf grid. Accept item count, item width and height, shelf width, and gap; return each item's row, column, and top-left coordinates plus the number of rows used. Use arithmetic and in-memory data only.
2. The Runner AI Created
AI also created run.ps1. It prepares the sample data, passes the parameters, and invokes the generated PowerShell.
The runtime, expected results, and safety boundaries were checked and recorded.
Validation StatusPassed
Runtime: PowerShell 7.6.6 Command: `./pwsh-runtime/pwsh -NoLogo -NoProfile -File run.ps1` Exit status: `0` Checks: seven items were placed in two columns and four rows with non-overlapping coordinates and the requested gap. Safety: deterministic arithmetic over in-memory parameters only; no network, credentials, deletion, or system changes.
Lab · 2026-09-22
Truth Table Composer
Compose a safe Boolean truth table with an explicit expression switch.
Validated
AI found the scenario, created the prompt and runner, generated the PowerShell, ran it, and validated the result.
PowerShell 7 implementation
1. The Prompt AI Created for This Idea
After finding the scenario, AI turned it into this concise prompt. That prompt was then used to generate the PowerShell.
Create a fully commented PowerShell 7 truth-table generator for two Boolean inputs. Accept a small expression using only `AND`, `OR`, `NOT`, `A`, and `B`; evaluate all four combinations with an explicit token switch, never dynamic code execution, and return readable rows. Keep it in memory and reject unsupported tokens.
2. The Runner AI Created
AI also created run.ps1. It prepares the sample data, passes the parameters, and invokes the generated PowerShell.
[CmdletBinding()]
param()
$ErrorActionPreference = 'Stop'
& (Join-Path $PSScriptRoot 'solution.ps1') -Expression 'A AND NOT B' | Format-Table -AutoSize
3. The PowerShell AI Generated
solution.ps1 is the runnable PowerShell produced from the AI-created prompt.
# Evaluate a deliberately small Boolean expression without dynamic execution.
[CmdletBinding()]
param([Parameter(Mandatory)][ValidateSet('A AND B','A OR B','A AND NOT B','NOT A OR B')][string] $Expression)
Set-StrictMode -Version Latest
function Test-Expression {
param([bool]$A,[bool]$B,[string]$Text)
switch ($Text) {
'A AND B' { return ($A -and $B) }
'A OR B' { return ($A -or $B) }
'A AND NOT B' { return ($A -and -not $B) }
'NOT A OR B' { return ((-not $A) -or $B) }
default { throw "Unsupported expression: $Text" }
}
}
# Enumerate every two-bit combination exactly once.
foreach ($a in $false,$true) {
foreach ($b in $false,$true) {
[pscustomobject]@{ A = $a; B = $b; Expression = $Expression; Result = Test-Expression -A $a -B $b -Text $Expression }
}
}
4. What Happened When It Ran
The actual captured output, errors, and exit status.
PowerShell version: 7.6.6
Command: ./pwsh-runtime/pwsh -NoLogo -NoProfile -File run.ps1
=== STDOUT ===
A B Expression Result
- - ---------- ------
False False A AND NOT B False
False True A AND NOT B False
True False A AND NOT B True
True True A AND NOT B False
=== STDERR ===
(empty)
=== EXIT STATUS ===
0
5. Validation Performed by the AI Workflow
The runtime, expected results, and safety boundaries were checked and recorded.
Validation StatusPassed
Runtime: PowerShell 7.6.6 Command: `./pwsh-runtime/pwsh -NoLogo -NoProfile -File run.ps1` Exit status: `0` Checks: all four Boolean combinations were evaluated for the allow-listed expression and the expected single true row was produced. Safety: explicit switch-based evaluation; no `Invoke-Expression`, network, credentials, deletion, or system changes.
Lab · 2026-09-23
Project Timeline Workbook
Turn fictional milestones into a two-sheet Excel planning workbook.
Validated
AI found the scenario, created the prompt and runner, generated the PowerShell, ran it, and validated the result.
PowerShell 7 implementation
1. The Prompt AI Created for This Idea
After finding the scenario, AI turned it into this concise prompt. That prompt was then used to generate the PowerShell.
Create a PowerShell 7 script that accepts milestone objects and an output path, calculates duration and progress, then uses ImportExcel to create Timeline and Summary worksheets. Freeze the header, format dates and percentages, and return a concise result object. Use only supplied sample data and write only the requested workbook.
2. The Runner AI Created
AI also created run.ps1. It prepares the sample data, passes the parameters, and invokes the generated PowerShell.
$ErrorActionPreference = 'Stop'
# Build fictional milestones so the example is reproducible and self-contained.
$milestones = @(
[pscustomobject]@{ Name = 'Discovery'; Owner = 'Mina'; Status = 'Done'; Start = '2026-09-07'; Finish = '2026-09-09'; Progress = 1.00 }
[pscustomobject]@{ Name = 'Prototype'; Owner = 'Kai'; Status = 'Active'; Start = '2026-09-10'; Finish = '2026-09-16'; Progress = 0.65 }
[pscustomobject]@{ Name = 'Pilot'; Owner = 'Nora'; Status = 'Planned'; Start = '2026-09-17'; Finish = '2026-09-23'; Progress = 0.00 }
[pscustomobject]@{ Name = 'Launch'; Owner = 'Mina'; Status = 'Planned'; Start = '2026-09-24'; Finish = '2026-09-25'; Progress = 0.00 }
)
$path = Join-Path $PSScriptRoot 'project-timeline.xlsx'
& (Join-Path $PSScriptRoot 'solution.ps1') -Milestone $milestones -OutputPath $path |
Format-List
3. The PowerShell AI Generated
solution.ps1 is the runnable PowerShell produced from the AI-created prompt.
[CmdletBinding()]
param(
# Accept milestone records from the runner instead of reading external systems.
[Parameter(Mandatory)]
[object[]] $Milestone,
# Keep the output destination explicit and controlled by the caller.
[Parameter(Mandatory)]
[string] $OutputPath
)
# Stop on module or workbook errors so validation receives a reliable exit status.
$ErrorActionPreference = 'Stop'
$WarningPreference = 'SilentlyContinue'
# Import the workbook module only when this solution is actually run.
Import-Module ImportExcel -ErrorAction Stop -WarningAction SilentlyContinue
# Normalize each milestone and calculate the fields readers need for planning.
$timeline = foreach ($item in $Milestone) {
$start = [datetime]$item.Start
$finish = [datetime]$item.Finish
$duration = [math]::Max(1, ($finish.Date - $start.Date).Days + 1)
# Emit a predictable record for the Timeline worksheet.
[pscustomobject]@{
Milestone = [string]$item.Name
Owner = [string]$item.Owner
Status = [string]$item.Status
Start = $start
Finish = $finish
DurationDays = $duration
Progress = [double]$item.Progress
}
}
# Group the normalized records to create a compact management summary.
$summary = $timeline |
Group-Object Status |
Sort-Object Name |
ForEach-Object {
[pscustomobject]@{
Status = $_.Name
MilestoneCount = $_.Count
AverageProgress = [math]::Round(($_.Group.Progress | Measure-Object -Average).Average, 2)
}
}
# Create the detailed worksheet with friendly table and column formatting.
$timeline | Export-Excel -Path $OutputPath -WorksheetName 'Timeline' -TableName 'ProjectTimeline' `
-FreezeTopRow -BoldTopRow -AutoFilter
# Append the summary worksheet and render Progress as a percentage.
$summary | Export-Excel -Path $OutputPath -WorksheetName 'Summary' -TableName 'StatusSummary' `
-FreezeTopRow -BoldTopRow -AutoFilter
# Apply focused formats rather than formatting every numeric cell the same way.
$package = Open-ExcelPackage -Path $OutputPath
Set-ExcelRange -Worksheet $package.Timeline -Range 'D2:E100' -NumberFormat 'yyyy-mm-dd'
Set-ExcelRange -Worksheet $package.Timeline -Range 'G2:G100' -NumberFormat '0%'
Set-ExcelRange -Worksheet $package.Summary -Range 'C2:C100' -NumberFormat '0%'
Close-ExcelPackage -ExcelPackage $package
# Return a small object that is easy for automation to inspect.
[pscustomobject]@{
Workbook = Split-Path -Leaf $OutputPath
MilestoneCount = $timeline.Count
StatusCount = $summary.Count
Exists = Test-Path -LiteralPath $OutputPath
}
4. What Happened When It Ran
The actual captured output, errors, and exit status.
Checks: Created project-timeline.xlsx, confirmed both Timeline and Summary worksheets, and read back milestone values from the workbook. Four milestones and three status groups matched the sample data.
Runtime note: The Linux image lacks the optional native library used for column autosizing. The lab avoids autosizing; workbook creation, focused formats, and read-back validation passed.
Safety: The solution uses supplied fictional data, performs no network access, and writes only the requested workbook.
Lab · 2026-09-23
Terminal Ripple Simulator
Render deterministic Unicode wave frames with bounded in-memory math.
Validated
AI found the scenario, created the prompt and runner, generated the PowerShell, ran it, and validated the result.
PowerShell 7 implementation
1. The Prompt AI Created for This Idea
After finding the scenario, AI turned it into this concise prompt. That prompt was then used to generate the PowerShell.
Create a PowerShell 7 function that renders a deterministic Unicode ripple simulation for a chosen width, height, and frame count. Use an in-memory wave formula, label every frame, return text only, and keep the run bounded with no sleeps, input, files, or network access.
2. The Runner AI Created
AI also created run.ps1. It prepares the sample data, passes the parameters, and invokes the generated PowerShell.
$ErrorActionPreference = 'Stop'
# Pass a compact canvas and three frames to keep validation output readable.
& (Join-Path $PSScriptRoot 'solution.ps1') -Width 28 -Height 9 -FrameCount 3
3. The PowerShell AI Generated
solution.ps1 is the runnable PowerShell produced from the AI-created prompt.
[CmdletBinding()]
param(
# Bound the canvas so automated runs remain small and predictable.
[ValidateRange(12, 60)]
[int] $Width = 32,
# Bound the vertical size for readable terminal output.
[ValidateRange(6, 24)]
[int] $Height = 10,
# Limit the number of frames rather than creating an endless animation.
[ValidateRange(1, 12)]
[int] $FrameCount = 4
)
# Arrange characters from calm water to a bright wave crest.
$palette = @(' ', '·', '░', '▒', '▓', '█')
# Use a fixed center so identical parameters always produce identical frames.
$centerX = ($Width - 1) / 2.0
$centerY = ($Height - 1) / 2.0
# Render each frame as text; no cursor movement or delay is required.
for ($frame = 0; $frame -lt $FrameCount; $frame++) {
"Frame {0:D2}" -f ($frame + 1)
for ($y = 0; $y -lt $Height; $y++) {
# Build one row efficiently before writing it to the pipeline.
$row = [System.Text.StringBuilder]::new()
for ($x = 0; $x -lt $Width; $x++) {
# Correct the horizontal aspect ratio so rings look circular in a terminal.
$dx = ($x - $centerX) * 0.55
$dy = $y - $centerY
$distance = [math]::Sqrt(($dx * $dx) + ($dy * $dy))
# Move the phase forward by a fixed amount for each frame.
$wave = ([math]::Sin(($distance * 1.35) - ($frame * 0.9)) + 1.0) / 2.0
$index = [math]::Min($palette.Count - 1, [math]::Floor($wave * $palette.Count))
[void]$row.Append($palette[$index])
}
$row.ToString()
}
# Separate captured frames without depending on terminal control sequences.
if ($frame -lt ($FrameCount - 1)) {
''
}
}
4. What Happened When It Ran
The actual captured output, errors, and exit status.
Checks: Captured three labeled frames at 28 × 9 characters. Repeated parameters produced a bounded sequence with consistent dimensions and visible phase movement.
Safety: In-memory mathematics and text output only; no delay, input, files, network access, or system changes.
Lab · 2026-09-23
Color Contrast Ratio Calculator
Measure fictional palette pairs and report readable contrast thresholds.
Validated
AI found the scenario, created the prompt and runner, generated the PowerShell, ran it, and validated the result.
PowerShell 7 implementation
1. The Prompt AI Created for This Idea
After finding the scenario, AI turned it into this concise prompt. That prompt was then used to generate the PowerShell.
Create a PowerShell 7 script that accepts objects with foreground and background hex colors, calculates relative luminance and contrast ratio, and reports large-text and normal-text pass results. Validate `#RRGGBB` input, use no external modules, and return structured objects without changing files or systems.
2. The Runner AI Created
AI also created run.ps1. It prepares the sample data, passes the parameters, and invokes the generated PowerShell.
Checks: Returned three assessments. White on #7C3AED produced 5.70 and passed both configured thresholds; #94A3B8 on #E2E8F0 produced 2.08 and failed both.
Safety: In-memory conversion and arithmetic only; no files, modules, network access, or system changes.
Lab · 2026-09-23
Script Safety Boundary Scanner
Review inert script text against a small, explainable safety policy.
Validated
AI found the scenario, created the prompt and runner, generated the PowerShell, ran it, and validated the result.
PowerShell 7 implementation
1. The Prompt AI Created for This Idea
After finding the scenario, AI turned it into this concise prompt. That prompt was then used to generate the PowerShell.
Create a PowerShell 7 script that scans named script-text samples against a small configurable set of risky-command patterns. Return severity, line number, rule, and evidence; never invoke, dot-source, or otherwise execute the text. Use no files, network calls, or system changes.
2. The Runner AI Created
AI also created run.ps1. It prepares the sample data, passes the parameters, and invokes the generated PowerShell.
Checks: The clean sample returned no configured matches. The two review samples produced four findings with the expected severity, rule, line, and evidence.
Safety: Script samples remained inert strings. The solution did not invoke, dot-source, parse, or otherwise execute them.
Lab · 2026-09-23
Feature Flag Rollout Simulator
Preview stable percentage rollouts with deterministic identity buckets.
Validated
AI found the scenario, created the prompt and runner, generated the PowerShell, ran it, and validated the result.
PowerShell 7 implementation
1. The Prompt AI Created for This Idea
After finding the scenario, AI turned it into this concise prompt. That prompt was then used to generate the PowerShell.
Create a PowerShell 7 script that assigns supplied user IDs to stable buckets from 0–99 using SHA-256 plus a feature key. For each requested rollout percentage, return the bucket and enabled state. Keep it deterministic, in memory, and free of network, file, or system changes.
2. The Runner AI Created
AI also created run.ps1. It prepares the sample data, passes the parameters, and invokes the generated PowerShell.
$ErrorActionPreference = 'Stop'
# Preview the same fictional cohort at three rollout stages.
& (Join-Path $PSScriptRoot 'solution.ps1') `
-UserId @('user-amber', 'user-cobalt', 'user-jade', 'user-silver') `
-FeatureKey 'navigation-refresh' `
-Percentage @(10, 35, 75) |
Format-Table -AutoSize
3. The PowerShell AI Generated
solution.ps1 is the runnable PowerShell produced from the AI-created prompt.
[CmdletBinding()]
param(
# Use fictional or non-sensitive identifiers supplied by the caller.
[Parameter(Mandatory)]
[string[]] $UserId,
# Salt the assignment by feature so separate rollouts distribute independently.
[Parameter(Mandatory)]
[string] $FeatureKey,
# Preview one or more bounded rollout percentages.
[Parameter(Mandatory)]
[ValidateRange(0, 100)]
[int[]] $Percentage
)
# Create one reusable SHA-256 instance for deterministic bucket assignment.
$sha256 = [System.Security.Cryptography.SHA256]::Create()
try {
foreach ($id in $UserId) {
# Combine feature and identity so the same feature/user pair stays stable.
$inputText = '{0}:{1}' -f $FeatureKey, $id
$bytes = [System.Text.Encoding]::UTF8.GetBytes($inputText)
$hash = $sha256.ComputeHash($bytes)
# Read the first four bytes in a fixed order and map them into 100 buckets.
[uint64]$value = ([uint64]$hash[0] -shl 24) -bor
([uint64]$hash[1] -shl 16) -bor
([uint64]$hash[2] -shl 8) -bor
[uint64]$hash[3]
$bucket = [int]($value % 100)
# Show how this stable assignment behaves at every requested threshold.
foreach ($level in ($Percentage | Sort-Object -Unique)) {
[pscustomobject]@{
Feature = $FeatureKey
UserId = $id
Bucket = $bucket
Percentage = $level
Enabled = $bucket -lt $level
}
}
}
}
finally {
# Dispose the cryptographic provider without changing any external state.
$sha256.Dispose()
}
4. What Happened When It Ran
The actual captured output, errors, and exit status.
Checks: Four identities retained one stable bucket across 10%, 35%, and 75% previews. Enabled state changed only when a threshold exceeded the assigned bucket.
Safety: Deterministic in-memory hashing only; no files, network access, credentials, or system changes.
The banner is the promise. This is the operating sequence behind each published lab: discover a small scenario, turn it into a concise prompt, generate PowerShell, run it safely, validate the evidence, and save everything together.
Build a first pass. Test it. Make it yours.
01FindSpot a useful idea
02PromptKeep the request concise
03GenerateCreate PowerShell 7
04RunUse sample data
05ValidateCheck output and safety
06PublishSave the complete lab
The through-line
Interesting problems, working examples.
The lab scans current technical conversations for approachable ideas, reframes them into original scenarios, and asks AI to make the concept concrete. The result is a small artifact you can read, copy, run, and adapt.
Everything here favors fictional or in-memory data and read-only behavior. The point is to make the idea visible without making your machine the experiment.
Open labs
Read the prompt. See how it runs.
AI found the scenario, created the prompt and runner, generated the PowerShell, ran it, and validated the result.
Lab · 2026-09-21
Terminal Constellation Renderer
Render a deterministic Unicode constellation storyboard as plain PowerShell terminal art.
Validated
AI found the scenario, created the prompt and runner, generated the PowerShell, ran it, and validated the result.
PowerShell 7 implementation
1. The Prompt AI Created for This Idea
After finding the scenario, AI turned it into the concise prompt used to generate the PowerShell.
Create a PowerShell 7 function that renders three deterministic frames of a star field as boxed Unicode terminal art. Accept width, height, frame count, and a random seed. Keep everything in memory, avoid cursor control and external access, and return the frames as text so the result is safe to capture non-interactively.
2. The Runner AI Created
AI created run.ps1 to prepare sample data, pass parameters, and invoke the generated PowerShell.
Runtime, expected results, and safety boundaries checked and recorded.
Validation StatusPassed
PowerShell 7.6.6 completed non-interactively with exit status 0 and no stderr output. three deterministic frames rendered with the requested 30 by 8 dimensions. bounded Unicode text generation in memory; no cursor control, network, credentials, deletion, or system changes.
three deterministic frames rendered with the requested 30 by 8 dimensions.
Safety
bounded Unicode text generation in memory; no cursor control, network, credentials, deletion, or system changes.
Lab · 2026-09-21
Milestone Risk Workbook
Turn fictional milestones into a formatted workbook with calculated risk and visual completion cues.
Review only
AI found the scenario, created the prompt and runner, generated the PowerShell, ran it, and validated the result.
PowerShell 7 implementation
1. The Prompt AI Created for This Idea
After finding the scenario, AI turned it into the concise prompt used to generate the PowerShell.
Using PowerShell 7 and ImportExcel, create a workbook from fictional milestones. Calculate days to due, classify each item as On Track, At Risk, or Late, add a completion data bar and status colors, and write a summary sheet. Use a caller-supplied path, sample objects only, and no network or system changes.
2. The Runner AI Created
AI created run.ps1 to prepare sample data, pass parameters, and invoke the generated PowerShell.
solution.ps1 is the runnable PowerShell produced from the AI-created prompt.
# Export milestone records as a small, review-ready Excel workbook.
# ImportExcel is the only external module used; all records are supplied by
# the caller and the workbook is written to the requested output path.
function Export-MilestoneRiskWorkbook {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[object[]]$Milestones,
[Parameter(Mandatory)]
[datetime]$AsOfDate,
[Parameter(Mandatory)]
[string]$Path
)
# Convert each input object to a consistent calculated record.
$rows = foreach ($milestone in $Milestones) {
$due = [datetime]$milestone.DueDate
$daysToDue = ($due.Date - $AsOfDate.Date).Days
$risk = if ($milestone.Status -eq 'Complete') { 'On Track' }
elseif ($daysToDue -lt 0) { 'Late' }
elseif ($daysToDue -le 3 -or $milestone.PercentComplete -lt 50) { 'At Risk' }
else { 'On Track' }
[pscustomobject]@{
Milestone = [string]$milestone.Milestone
Owner = [string]$milestone.Owner
DueDate = $due.Date
Status = [string]$milestone.Status
PercentComplete = [int]$milestone.PercentComplete
DaysToDue = $daysToDue
Risk = $risk
}
}
# Ensure the destination folder exists without touching any other files.
$parent = Split-Path -Parent $Path
if ($parent -and -not (Test-Path -LiteralPath $parent)) {
New-Item -ItemType Directory -Path $parent -Force | Out-Null
}
# Export the detailed table and a compact summary sheet.
$rows | Export-Excel -Path $Path -WorksheetName 'Milestones' -TableName 'Milestones' -AutoSize -FreezeTopRow -BoldTopRow -ClearSheet
$summary = $rows | Group-Object Risk | ForEach-Object {
[pscustomobject]@{ Risk = $_.Name; Count = $_.Count }
}
$summary | Export-Excel -Path $Path -WorksheetName 'Summary' -TableName 'RiskSummary' -AutoSize -BoldTopRow -Append
# Apply simple, portable visual cues to make review faster.
$package = Open-ExcelPackage -Path $Path
$sheet = $package.Workbook.Worksheets['Milestones']
Add-ConditionalFormatting -Worksheet $sheet -Address 'E2:E200' -DataBarColor '4F81BD' | Out-Null
Add-ConditionalFormatting -Worksheet $sheet -Address 'G2:G200' -RuleType Equal -ConditionValue '"Late"' -BackgroundColor 'F4CCCC' -ForegroundColor '9C0006' | Out-Null
Add-ConditionalFormatting -Worksheet $sheet -Address 'G2:G200' -RuleType Equal -ConditionValue '"At Risk"' -BackgroundColor 'FFF2CC' -ForegroundColor '7F6000' | Out-Null
Close-ExcelPackage $package
[pscustomobject]@{
Path = (Resolve-Path -LiteralPath $Path).Path
MilestoneCount = $rows.Count
RiskSummary = (($summary | ForEach-Object { "$($_.Risk)=$($_.Count)" }) -join ', ')
}
}
4. What Happened When It Ran
Captured output, errors, and exit status from the runner.
PowerShell version: 7.6.6
Command: ./pwsh-runtime/pwsh -NoLogo -NoProfile -File run.ps1
Exit status: 1
PowerShell version verified separately: 7.6.6
Standard output: (empty)
Standard error:
Import-Module: run.ps1:3
The specified module 'ImportExcel' was not loaded because no valid module file was found in any module directory.
The workflow attempted to install ImportExcel, but the cloud runtime could not reach a package source. No workbook output was fabricated.
5. Validation Performed by the AI Workflow
Runtime, expected results, and safety boundaries checked and recorded.
Validation StatusReview only
The cloud runtime could not install or load ImportExcel, so this workbook lab remains review-only and no workbook output is claimed. The script uses fictional milestone objects and is ready for a runtime with the module available.
the script was reviewed for bounded, sample-only behavior but was not allowed to pretend that Excel export succeeded.
Safety
the intended workbook uses fictional objects and a caller path; no network, credentials, deletion, or system changes are performed by the solution.
Lab · 2026-09-21
Recipe Batch Scaler
Scale ingredient quantities to a new serving count while preserving units and decimal precision.
Validated
AI found the scenario, created the prompt and runner, generated the PowerShell, ran it, and validated the result.
PowerShell 7 implementation
1. The Prompt AI Created for This Idea
After finding the scenario, AI turned it into the concise prompt used to generate the PowerShell.
Create a PowerShell 7 function that scales a fictional recipe from its original serving count to a requested count. Accept ingredient objects with quantity, unit, and name; multiply quantities with decimal precision; and return a readable ingredient list. Use in-memory data only and reject zero or negative servings.
2. The Runner AI Created
AI created run.ps1 to prepare sample data, pass parameters, and invoke the generated PowerShell.
# Scale a fictional soup recipe from four portions to ten.
$ErrorActionPreference = 'Stop'
. (Join-Path $PSScriptRoot 'solution.ps1')
$ingredients = @(
[pscustomobject]@{ Quantity = 2; Unit = 'cups'; Ingredient = 'tomatoes' }
[pscustomobject]@{ Quantity = 1.5; Unit = 'cups'; Ingredient = 'stock' }
[pscustomobject]@{ Quantity = 0.5; Unit = 'cup'; Ingredient = 'lentils' }
[pscustomobject]@{ Quantity = 2; Unit = 'tbsp'; Ingredient = 'herbs' }
)
Convert-RecipeBatch -OriginalServings 4 -TargetServings 10 -Ingredients $ingredients | Format-Table -AutoSize
3. The PowerShell AI Generated
solution.ps1 is the runnable PowerShell produced from the AI-created prompt.
# Scale ingredient quantities while retaining the original units and names.
function Convert-RecipeBatch {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[ValidateRange(1,10000)]
[int]$OriginalServings,
[Parameter(Mandatory)]
[ValidateRange(1,10000)]
[int]$TargetServings,
[Parameter(Mandatory)]
[object[]]$Ingredients
)
# One multiplier applies to every ingredient in the batch.
$multiplier = [decimal]$TargetServings / $OriginalServings
foreach ($ingredient in $Ingredients) {
# Round display quantities to three decimal places but keep decimals.
$quantity = [Math]::Round(([decimal]$ingredient.Quantity * $multiplier), 3)
[pscustomobject]@{
Quantity = $quantity
Unit = [string]$ingredient.Unit
Ingredient = [string]$ingredient.Ingredient
}
}
}
4. What Happened When It Ran
Captured output, errors, and exit status from the runner.
PowerShell version: 7.6.6
Command: ./pwsh-runtime/pwsh -NoLogo -NoProfile -File run.ps1
Exit status: 0
Standard error: (empty)
Standard output:
Quantity Unit Ingredient
-------- ---- ----------
5.00 cups tomatoes
3.75 cups stock
1.25 cup lentils
5.00 tbsp herbs
5. Validation Performed by the AI Workflow
Runtime, expected results, and safety boundaries checked and recorded.
Validation StatusPassed
PowerShell 7.6.6 completed non-interactively with exit status 0 and no stderr output. four ingredients scaled from four to ten servings with decimal quantities preserved. in-memory sample data only; no network, credentials, deletion, or system changes.
four ingredients scaled from four to ten servings with decimal quantities preserved.
Safety
in-memory sample data only; no network, credentials, deletion, or system changes.
Lab · 2026-09-21
Global Launch Board
Translate fictional UTC launch events into a readable schedule for distributed teams.
Validated
AI found the scenario, created the prompt and runner, generated the PowerShell, ran it, and validated the result.
PowerShell 7 implementation
1. The Prompt AI Created for This Idea
After finding the scenario, AI turned it into the concise prompt used to generate the PowerShell.
Create a PowerShell 7 function that accepts fictional launch events as UTC timestamps and converts each one to a caller-supplied list of time zones. Return event name, zone, local timestamp, and local date. Use `TimeZoneInfo`, in-memory data, and no network or system access.
2. The Runner AI Created
AI created run.ps1 to prepare sample data, pass parameters, and invoke the generated PowerShell.
solution.ps1 is the runnable PowerShell produced from the AI-created prompt.
# Convert UTC launch events into a compact multi-zone schedule.
function Get-GlobalLaunchBoard {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[object[]]$Events,
[Parameter(Mandatory)]
[string[]]$TimeZoneIds
)
foreach ($event in $Events) {
# Parse as an offset-aware instant so the conversion is unambiguous.
$utc = [datetimeoffset]$event.UtcTime
foreach ($zoneId in $TimeZoneIds) {
$zone = [TimeZoneInfo]::FindSystemTimeZoneById($zoneId)
$local = [TimeZoneInfo]::ConvertTime($utc, $zone)
[pscustomobject]@{
Event = [string]$event.Event
Zone = $zone.Id
LocalTime = $local.ToString('yyyy-MM-dd HH:mm zzz')
LocalDate = $local.ToString('dddd, MMM d')
}
}
}
}
4. What Happened When It Ran
Captured output, errors, and exit status from the runner.
PowerShell version: 7.6.6
Command: ./pwsh-runtime/pwsh -NoLogo -NoProfile -File run.ps1
Exit status: 0
Standard error: (empty)
Standard output:
Event Zone LocalTime LocalDate
----- ---- --------- ---------
Preview stream America/New_York 2026-10-03 11:00 -04:00 Saturday, Oct 3
Preview stream Europe/London 2026-10-03 16:00 +01:00 Saturday, Oct 3
Preview stream Asia/Tokyo 2026-10-04 00:00 +09:00 Sunday, Oct 4
Feedback room America/New_York 2026-10-04 05:30 -04:00 Sunday, Oct 4
Feedback room Europe/London 2026-10-04 10:30 +01:00 Sunday, Oct 4
Feedback room Asia/Tokyo 2026-10-04 18:30 +09:00 Sunday, Oct 4
5. Validation Performed by the AI Workflow
Runtime, expected results, and safety boundaries checked and recorded.
Validation StatusPassed
PowerShell 7.6.6 completed non-interactively with exit status 0 and no stderr output. two UTC events produced six rows across three time zones; local dates and offsets were populated. deterministic in-memory objects only; no network, credentials, deletion, or system changes.
two UTC events produced six rows across three time zones; local dates and offsets were populated.
Safety
deterministic in-memory objects only; no network, credentials, deletion, or system changes.
Lab · 2026-09-21
Word Ladder Puzzle
Solve a compact word ladder with a breadth-first search written in PowerShell.
Validated
AI found the scenario, created the prompt and runner, generated the PowerShell, ran it, and validated the result.
PowerShell 7 implementation
1. The Prompt AI Created for This Idea
After finding the scenario, AI turned it into the concise prompt used to generate the PowerShell.
Create a PowerShell 7 breadth-first word-ladder solver. Accept a start word, end word, and same-length dictionary; change one letter at a time; return whether a path exists, its step count, and the shortest path. Keep the dictionary in memory and avoid external access.
2. The Runner AI Created
AI created run.ps1 to prepare sample data, pass parameters, and invoke the generated PowerShell.
solution.ps1 is the runnable PowerShell produced from the AI-created prompt.
# Find the shortest one-letter-at-a-time transformation between two words.
function Find-WordLadder {
[CmdletBinding()]
param(
[Parameter(Mandatory)] [string]$StartWord,
[Parameter(Mandatory)] [string]$EndWord,
[Parameter(Mandatory)] [string[]]$WordList
)
$start = $StartWord.ToLowerInvariant()
$end = $EndWord.ToLowerInvariant()
if ($start.Length -ne $end.Length) { throw 'Start and end words must have the same length.' }
# Keep only same-length words and use sets for constant-time membership.
$dictionary = [System.Collections.Generic.HashSet[string]]::new([StringComparer]::OrdinalIgnoreCase)
$WordList | Where-Object { $_.Length -eq $start.Length } | ForEach-Object { [void]$dictionary.Add($_.ToLowerInvariant()) }
[void]$dictionary.Add($start)
[void]$dictionary.Add($end)
# Queue words breadth-first and remember each predecessor for reconstruction.
$queue = [System.Collections.Generic.Queue[string]]::new()
$visited = [System.Collections.Generic.HashSet[string]]::new([StringComparer]::OrdinalIgnoreCase)
$parent = @{}
$queue.Enqueue($start)
[void]$visited.Add($start)
$alphabet = 'abcdefghijklmnopqrstuvwxyz'.ToCharArray()
while ($queue.Count -gt 0) {
$current = $queue.Dequeue()
if ($current -eq $end) { break }
for ($position = 0; $position -lt $current.Length; $position++) {
foreach ($letter in $alphabet) {
if ($letter -eq $current[$position]) { continue }
$candidateChars = $current.ToCharArray()
$candidateChars[$position] = $letter
$candidate = -join $candidateChars
if ($dictionary.Contains($candidate) -and $visited.Add($candidate)) {
$parent[$candidate] = $current
$queue.Enqueue($candidate)
}
}
}
}
if (-not $visited.Contains($end)) {
return [pscustomobject]@{ Start = $start; End = $end; Found = $false; Steps = 0; Path = @() }
}
$path = [System.Collections.Generic.List[string]]::new()
$cursor = $end
while ($null -ne $cursor) {
$path.Insert(0, $cursor)
$cursor = if ($parent.ContainsKey($cursor)) { $parent[$cursor] } else { $null }
}
[pscustomobject]@{ Start = $start; End = $end; Found = $true; Steps = $path.Count - 1; Path = $path.ToArray() }
}
4. What Happened When It Ran
Captured output, errors, and exit status from the runner.
PowerShell version: 7.6.6
Command: ./pwsh-runtime/pwsh -NoLogo -NoProfile -File run.ps1
Exit status: 0
Standard error: (empty)
Standard output:
Start : cold
End : warm
Found : True
Steps : 4
Path : {cold, cord, word, ward…}
Path: cold -> cord -> word -> ward -> warm
5. Validation Performed by the AI Workflow
Runtime, expected results, and safety boundaries checked and recorded.
Validation StatusPassed
PowerShell 7.6.6 completed non-interactively with exit status 0 and no stderr output. breadth-first search found a four-step shortest path from `cold` to `warm`. bounded in-memory dictionary only; no network, credentials, deletion, or system changes.
breadth-first search found a four-step shortest path from `cold` to `warm`.
Safety
bounded in-memory dictionary only; no network, credentials, deletion, or system changes.
Lab · 2026-09-20
Compound Storage Growth Forecast
Project compounded capacity growth for fictional storage workloads.
Validated
PowerShell 7 implementation
1. The Prompt AI Created for This Idea
After finding the scenario, AI turned it into this concise prompt. That prompt was then used to generate the PowerShell.
Create a fully commented PowerShell 7 function that accepts storage workloads with a name, starting gigabytes, monthly growth percentage, and forecast length. Calculate compounded final size, added capacity, and average monthly growth. Validate numeric inputs and return sortable objects. Use only in-memory data with no network or system changes.
2. The Runner AI Created
AI also created run.ps1. It prepares the sample data, passes the parameters, and invokes the generated PowerShell.
$ErrorActionPreference = 'Stop'
# Load the AI-generated function from the same lab folder.
. "$PSScriptRoot/solution.ps1"
# Create deterministic fictional workloads entirely in memory.
$workloads = @(
[pscustomobject]@{ Name = 'Build Artifacts'; StartingGB = 420; MonthlyGrowthPct = 8; Months = 6 }
[pscustomobject]@{ Name = 'Support Archive'; StartingGB = 850; MonthlyGrowthPct = 3.5; Months = 12 }
[pscustomobject]@{ Name = 'Design Assets'; StartingGB = 275; MonthlyGrowthPct = 12; Months = 4 }
)
# Generate the forecast and show the highest final capacity first.
Get-StorageGrowthForecast -Workload $workloads |
Sort-Object FinalGB -Descending |
Select-Object Workload, StartingGB,
@{ Name = 'GrowthPct'; Expression = { $_.MonthlyGrowthPercent } },
Months, FinalGB, AddedGB,
@{ Name = 'AvgAddedGB'; Expression = { $_.AverageAddedGB } } |
Format-Table -AutoSize
3. The PowerShell AI Generated
solution.ps1 is the runnable PowerShell produced from the AI-created prompt.
function Get-StorageGrowthForecast {
[CmdletBinding()]
param(
# Each input object describes one fictional workload and its growth assumptions.
[Parameter(Mandatory, ValueFromPipeline)]
[psobject[]]$Workload
)
process {
foreach ($item in $Workload) {
# Convert each numeric field once so calculations use predictable decimal values.
$startingGB = [double]$item.StartingGB
$growthPct = [double]$item.MonthlyGrowthPct
$months = [int]$item.Months
# Reject values that would make the forecast misleading or mathematically invalid.
if ([string]::IsNullOrWhiteSpace([string]$item.Name)) {
throw 'Each workload must have a name.'
}
if ($startingGB -lt 0 -or $growthPct -lt 0 -or $months -lt 1) {
throw "Workload '$($item.Name)' contains an invalid numeric value."
}
# Convert the percentage to a multiplier and compound it for the requested months.
$monthlyMultiplier = 1 + ($growthPct / 100)
$finalGB = $startingGB * [math]::Pow($monthlyMultiplier, $months)
$addedGB = $finalGB - $startingGB
# Return a clean object that downstream commands can sort, export, or format.
[pscustomobject]@{
Workload = [string]$item.Name
StartingGB = [math]::Round($startingGB, 2)
MonthlyGrowthPercent = [math]::Round($growthPct, 2)
Months = $months
FinalGB = [math]::Round($finalGB, 2)
AddedGB = [math]::Round($addedGB, 2)
AverageAddedGB = [math]::Round($addedGB / $months, 2)
}
}
}
}
4. What Happened When It Ran
The actual captured output, errors, and exit status.
three workloads were returned in descending final-size order; a focused assertion verified the six-month compounded result of 666.49 GB for Build Artifacts.
Safety
fictional in-memory objects only; no network, file writes, deletion, registry/system changes, credential access, or arbitrary code execution.
Lab · 2026-09-20
Service Renewal Workbook
Build a formatted Excel renewal tracker with calculated status and visual cues.
Validated
PowerShell 7 implementation
1. The Prompt AI Created for This Idea
After finding the scenario, AI turned it into this concise prompt. That prompt was then used to generate the PowerShell.
Create a fully commented PowerShell 7 function using ImportExcel that accepts fictional service renewals and an as-of date. Calculate days remaining and a status of Expired, Due Soon, or Scheduled. Export a formatted Excel table, color the status cells, and return a summary object. Only create the requested workbook; do not use network, credentials, or system settings.
2. The Runner AI Created
AI also created run.ps1. It prepares the sample data, passes the parameters, and invokes the generated PowerShell.
$ErrorActionPreference = 'Stop'
# Suppress the module's optional AutoSize dependency warning; this lab sets widths explicitly.
$WarningPreference = 'SilentlyContinue'
# Load the AI-generated workbook function.
. "$PSScriptRoot/solution.ps1"
# Use fixed fictional records so every run produces the same status counts.
$renewals = @(
[pscustomobject]@{ Service = 'Diagram Cloud'; Owner = 'Design'; RenewalDate = '2026-09-12'; AnnualCost = 1440 }
[pscustomobject]@{ Service = 'Build Cache'; Owner = 'Engineering'; RenewalDate = '2026-09-28'; AnnualCost = 3600 }
[pscustomobject]@{ Service = 'Survey Desk'; Owner = 'Research'; RenewalDate = '2026-10-14'; AnnualCost = 960 }
[pscustomobject]@{ Service = 'Status Board'; Owner = 'Operations'; RenewalDate = '2027-01-10'; AnnualCost = 2280 }
)
# Create a new workbook in the process temp directory without overwriting prior runs.
$runId = [guid]::NewGuid().ToString('N').Substring(0, 8)
$workbookPath = Join-Path ([System.IO.Path]::GetTempPath()) "service-renewal-workbook-$runId.xlsx"
$summary = Export-ServiceRenewalWorkbook -Renewal $renewals -AsOfDate '2026-09-20' -Path $workbookPath
# Show both the summary and workbook structure used by validation.
$summary | Format-List
$package = Open-ExcelPackage -Path $workbookPath
$sheet = $package.Workbook.Worksheets['Renewals']
[pscustomobject]@{
Worksheet = $sheet.Name
Rows = $sheet.Dimension.Rows
Columns = $sheet.Dimension.Columns
Tables = $sheet.Tables.Count
ConditionalFormats = $sheet.ConditionalFormatting.Count
} | Format-List
Close-ExcelPackage -ExcelPackage $package -NoSave
3. The PowerShell AI Generated
solution.ps1 is the runnable PowerShell produced from the AI-created prompt.
function Export-ServiceRenewalWorkbook {
[CmdletBinding()]
param(
# Renewal records must include Service, Owner, RenewalDate, and AnnualCost.
[Parameter(Mandatory)]
[psobject[]]$Renewal,
# A fixed as-of date keeps the calculation deterministic and easy to test.
[Parameter(Mandatory)]
[datetime]$AsOfDate,
# The caller chooses the single workbook file this function creates.
[Parameter(Mandatory)]
[string]$Path
)
# Fail clearly when the lab's only external module is unavailable.
if (-not (Get-Module -ListAvailable -Name ImportExcel)) {
throw 'The ImportExcel module is required.'
}
Import-Module ImportExcel -ErrorAction Stop -WarningAction SilentlyContinue
# Enrich each fictional renewal with deterministic scheduling fields.
$report = foreach ($item in $Renewal) {
$renewalDate = [datetime]$item.RenewalDate
$daysRemaining = [int][math]::Floor(($renewalDate.Date - $AsOfDate.Date).TotalDays)
# Assign a small set of statuses that work well for filtering and formatting.
$status = if ($daysRemaining -lt 0) {
'Expired'
}
elseif ($daysRemaining -le 30) {
'Due Soon'
}
else {
'Scheduled'
}
# Emit only the columns intended for the finished workbook.
[pscustomobject]@{
Service = [string]$item.Service
Owner = [string]$item.Owner
RenewalDate = $renewalDate.Date
DaysRemaining = $daysRemaining
AnnualCost = [decimal]$item.AnnualCost
Status = $status
}
}
# Export the records as a named table and retain the package for final styling.
$excel = $report |
Sort-Object RenewalDate |
Export-Excel -Path $Path -WorksheetName 'Renewals' -TableName 'RenewalTable' `
-TableStyle Medium2 -FreezeTopRow -BoldTopRow -PassThru
# Apply readable formats to the date and currency columns.
$worksheet = $excel.Workbook.Worksheets['Renewals']
Set-ExcelRange -Worksheet $worksheet -Range 'C:C' -NumberFormat 'yyyy-mm-dd'
Set-ExcelRange -Worksheet $worksheet -Range 'E:E' -NumberFormat '$#,##0.00'
# Set practical widths explicitly so the workbook is portable across cloud hosts.
Set-ExcelRange -Worksheet $worksheet -Range 'A:A' -Width 22
Set-ExcelRange -Worksheet $worksheet -Range 'B:B' -Width 16
Set-ExcelRange -Worksheet $worksheet -Range 'C:F' -Width 18
# Color the status column so urgent items are visible at a glance.
Add-ConditionalFormatting -Worksheet $worksheet -Range 'F2:F1048576' `
-RuleType ContainsText -ConditionValue 'Expired' -BackgroundColor 'LightPink' -Bold
Add-ConditionalFormatting -Worksheet $worksheet -Range 'F2:F1048576' `
-RuleType ContainsText -ConditionValue 'Due Soon' -BackgroundColor 'LightYellow' -Bold
Add-ConditionalFormatting -Worksheet $worksheet -Range 'F2:F1048576' `
-RuleType ContainsText -ConditionValue 'Scheduled' -BackgroundColor 'LightGreen'
# Save and close the package before returning a concise execution summary.
Close-ExcelPackage -ExcelPackage $excel
[pscustomobject]@{
Path = $Path
RecordCount = $report.Count
ExpiredCount = @($report | Where-Object Status -eq 'Expired').Count
DueSoonCount = @($report | Where-Object Status -eq 'Due Soon').Count
ScheduledCount = @($report | Where-Object Status -eq 'Scheduled').Count
TotalAnnualCost = [math]::Round(($report | Measure-Object AnnualCost -Sum).Sum, 2)
}
}
4. What Happened When It Ran
The actual captured output, errors, and exit status.
four records produced the expected 1 expired, 2 due-soon, and 1 scheduled statuses; the workbook reopened successfully with 5 rows, 6 columns, 1 named table, and 3 conditional-formatting rules.
Safety
fictional input only; the script created one uniquely named workbook in the temporary directory and made no network calls, deletions, registry/system changes, credential accesses, or arbitrary code executions.
Lab · 2026-09-20
Human-Friendly Axis Scale
Turn arbitrary numeric ranges into clean chart bounds and readable tick labels.
Validated
PowerShell 7 implementation
1. The Prompt AI Created for This Idea
After finding the scenario, AI turned it into this concise prompt. That prompt was then used to generate the PowerShell.
Create a fully commented PowerShell 7 function that converts a numeric minimum and maximum into human-friendly chart bounds and tick labels. Choose a 1, 2, 5, or 10 interval near a requested tick count, include zero when requested, and return one summary object. Use only deterministic in-memory calculations.
2. The Runner AI Created
AI also created run.ps1. It prepares the sample data, passes the parameters, and invokes the generated PowerShell.
solution.ps1 is the runnable PowerShell produced from the AI-created prompt.
function Get-FriendlyAxisScale {
[CmdletBinding()]
param(
# The smallest and largest values that must fit on the axis.
[Parameter(Mandatory)]
[double]$Minimum,
[Parameter(Mandatory)]
[double]$Maximum,
# This is a target, because clean intervals matter more than an exact count.
[ValidateRange(2, 20)]
[int]$TargetTickCount = 6,
# This switch is useful for charts where distance from zero has meaning.
[switch]$IncludeZero
)
# Reject an empty or reversed numeric range before calculating an interval.
if ($Maximum -le $Minimum) {
throw 'Maximum must be greater than Minimum.'
}
# Expand the source range to zero when the caller requests that visual baseline.
$workingMinimum = if ($IncludeZero -and $Minimum -gt 0) { 0 } else { $Minimum }
$workingMaximum = if ($IncludeZero -and $Maximum -lt 0) { 0 } else { $Maximum }
# Estimate an interval, then split it into a power of ten and a small fraction.
$rawInterval = ($workingMaximum - $workingMinimum) / ($TargetTickCount - 1)
$magnitude = [math]::Pow(10, [math]::Floor([math]::Log10($rawInterval)))
$fraction = $rawInterval / $magnitude
# Choose the next familiar interval so labels stay readable and cover the range.
$niceFraction = if ($fraction -le 1) {
1
}
elseif ($fraction -le 2) {
2
}
elseif ($fraction -le 5) {
5
}
else {
10
}
$interval = $niceFraction * $magnitude
# Round outward so the original minimum and maximum always remain visible.
$axisMinimum = [math]::Floor($workingMinimum / $interval) * $interval
$axisMaximum = [math]::Ceiling($workingMaximum / $interval) * $interval
# Derive an appropriate label precision for intervals smaller than one.
$decimals = if ($interval -lt 1) {
[math]::Max(0, [int](-[math]::Floor([math]::Log10($interval))))
}
else {
0
}
# Build both numeric tick values and ready-to-display invariant labels.
$ticks = [System.Collections.Generic.List[double]]::new()
$labels = [System.Collections.Generic.List[string]]::new()
for ($value = $axisMinimum; $value -le ($axisMaximum + ($interval / 1000)); $value += $interval) {
$rounded = [math]::Round($value, $decimals)
$ticks.Add($rounded)
$labels.Add($rounded.ToString("F$decimals", [cultureinfo]::InvariantCulture))
}
# Return one object that a charting layer can consume without reparsing text.
[pscustomobject]@{
SourceMinimum = $Minimum
SourceMaximum = $Maximum
AxisMinimum = $axisMinimum
AxisMaximum = $axisMaximum
Interval = $interval
TickCount = $ticks.Count
Ticks = $ticks.ToArray()
Labels = $labels.ToArray()
}
}
4. What Happened When It Ran
The actual captured output, errors, and exit status.
three ranges produced ordered ticks that covered every source value; a focused assertion verified zero inclusion, bounds of 0 through 100, and six ticks for the queue-depth example.
Safety
deterministic in-memory calculations only; no network, file writes, deletion, registry/system changes, credential access, or arbitrary code execution.
Lab · 2026-09-20
2D Transform Matrix Composer
Compose ordered scale, rotation, and translation operations for layout points.
Validated
PowerShell 7 implementation
1. The Prompt AI Created for This Idea
After finding the scenario, AI turned it into this concise prompt. That prompt was then used to generate the PowerShell.
Create fully commented PowerShell 7 functions that compose ordered 2D scale, rotate, and translate operations into one affine matrix, then apply it to named points. Return the combined matrix and rounded transformed coordinates. Validate operation names and use only in-memory sample data.
2. The Runner AI Created
AI also created run.ps1. It prepares the sample data, passes the parameters, and invokes the generated PowerShell.
$ErrorActionPreference = 'Stop'
# Load the AI-generated matrix functions.
. "$PSScriptRoot/solution.ps1"
# Describe the four corners of a fictional layout panel.
$points = @(
[pscustomobject]@{ Name = 'TopLeft'; X = 0; Y = 0 }
[pscustomobject]@{ Name = 'TopRight'; X = 4; Y = 0 }
[pscustomobject]@{ Name = 'BottomRight'; X = 4; Y = 2 }
[pscustomobject]@{ Name = 'BottomLeft'; X = 0; Y = 2 }
)
# Scale first, rotate second, and translate the finished shape last.
$operations = @(
[pscustomobject]@{ Type = 'Scale'; X = 1.5; Y = 2 }
[pscustomobject]@{ Type = 'Rotate'; Degrees = 30 }
[pscustomobject]@{ Type = 'Translate'; X = 10; Y = 5 }
)
$result = Invoke-PointTransform -Point $points -Operation $operations
'Combined matrix'
$result.Matrix | Format-List
'Transformed points'
$result.Points | Format-Table -AutoSize
3. The PowerShell AI Generated
solution.ps1 is the runnable PowerShell produced from the AI-created prompt.
function New-AffineMatrix {
# Create a compact matrix object using the common six-value 2D representation.
param(
[double]$A = 1,
[double]$B = 0,
[double]$C = 0,
[double]$D = 1,
[double]$Tx = 0,
[double]$Ty = 0
)
[pscustomobject]@{ A = $A; B = $B; C = $C; D = $D; Tx = $Tx; Ty = $Ty }
}
function Join-AffineMatrix {
# Multiply two matrices so Right is applied first and Left is applied second.
param(
[Parameter(Mandatory)][psobject]$Left,
[Parameter(Mandatory)][psobject]$Right
)
New-AffineMatrix `
-A (($Left.A * $Right.A) + ($Left.C * $Right.B)) `
-B (($Left.B * $Right.A) + ($Left.D * $Right.B)) `
-C (($Left.A * $Right.C) + ($Left.C * $Right.D)) `
-D (($Left.B * $Right.C) + ($Left.D * $Right.D)) `
-Tx (($Left.A * $Right.Tx) + ($Left.C * $Right.Ty) + $Left.Tx) `
-Ty (($Left.B * $Right.Tx) + ($Left.D * $Right.Ty) + $Left.Ty)
}
function Invoke-PointTransform {
[CmdletBinding()]
param(
# Named input points make the output easier to compare with the source shape.
[Parameter(Mandatory)]
[psobject[]]$Point,
# Operations are applied in the exact order supplied by the caller.
[Parameter(Mandatory)]
[psobject[]]$Operation
)
# Start with an identity matrix that leaves every coordinate unchanged.
$combined = New-AffineMatrix
foreach ($item in $Operation) {
# Build the matrix for this operation without changing the input objects.
$operationMatrix = switch ([string]$item.Type) {
'Scale' {
New-AffineMatrix -A ([double]$item.X) -D ([double]$item.Y)
break
}
'Rotate' {
$radians = [double]$item.Degrees * [math]::PI / 180
$cosine = [math]::Cos($radians)
$sine = [math]::Sin($radians)
New-AffineMatrix -A $cosine -B $sine -C (-$sine) -D $cosine
break
}
'Translate' {
New-AffineMatrix -Tx ([double]$item.X) -Ty ([double]$item.Y)
break
}
default {
throw "Unsupported transform type '$($item.Type)'."
}
}
# Pre-multiply so the operations retain the caller's left-to-right order.
$combined = Join-AffineMatrix -Left $operationMatrix -Right $combined
}
# Apply the one combined matrix to every point and round only the public result.
$transformed = foreach ($item in $Point) {
$x = [double]$item.X
$y = [double]$item.Y
[pscustomobject]@{
Name = [string]$item.Name
SourceX = $x
SourceY = $y
ResultX = [math]::Round(($combined.A * $x) + ($combined.C * $y) + $combined.Tx, 3)
ResultY = [math]::Round(($combined.B * $x) + ($combined.D * $y) + $combined.Ty, 3)
}
}
# Return the reusable matrix and transformed points together as one result.
[pscustomobject]@{
Matrix = [pscustomobject]@{
A = [math]::Round($combined.A, 6)
B = [math]::Round($combined.B, 6)
C = [math]::Round($combined.C, 6)
D = [math]::Round($combined.D, 6)
Tx = [math]::Round($combined.Tx, 6)
Ty = [math]::Round($combined.Ty, 6)
}
Points = @($transformed)
}
}
4. What Happened When It Ran
The actual captured output, errors, and exit status.
four corners were transformed by the composed scale, rotation, and translation matrix; a focused assertion verified the transformed top-right point at approximately `(15.196, 8)`.
Safety
fictional in-memory points and operations only; no network, file writes, deletion, registry/system changes, credential access, or arbitrary code execution.
Lab · 2026-09-20
Runtime Compatibility Report
Match fictional automation jobs to the lowest compatible PowerShell runtime.
Validated
PowerShell 7 implementation
1. The Prompt AI Created for This Idea
After finding the scenario, AI turned it into this concise prompt. That prompt was then used to generate the PowerShell.
Create a fully commented PowerShell 7 function that accepts fictional jobs with minimum PowerShell versions plus an available runtime inventory. Select the lowest compatible runtime for each job, or report Upgrade Required. Return sortable objects and a reason for every decision. Do not inspect or change the host system.
2. The Runner AI Created
AI also created run.ps1. It prepares the sample data, passes the parameters, and invokes the generated PowerShell.
$ErrorActionPreference = 'Stop'
# Load the AI-generated compatibility function.
. "$PSScriptRoot/solution.ps1"
# Define a fictional runtime inventory instead of probing the current machine.
$availableRuntimes = [version[]]@('7.2.24', '7.4.13', '7.6.6')
# Give each sample job a different minimum runtime expectation.
$jobs = @(
[pscustomobject]@{ Name = 'Archive Indexer'; MinimumVersion = '7.2.0' }
[pscustomobject]@{ Name = 'Report Composer'; MinimumVersion = '7.4.2' }
[pscustomobject]@{ Name = 'Parallel Analyzer'; MinimumVersion = '7.6.0' }
[pscustomobject]@{ Name = 'Future Syntax Check'; MinimumVersion = '7.7.0' }
)
# Put unresolved jobs first, then render each decision without clipped columns.
$report = Get-RuntimeCompatibilityReport -Job $jobs -AvailableRuntime $availableRuntimes |
Sort-Object @{ Expression = { $_.Status -eq 'Ready' } }, Job
foreach ($item in $report) {
$item | Format-List Job, MinimumVersion, SelectedRuntime, Status, Reason
}
3. The PowerShell AI Generated
solution.ps1 is the runnable PowerShell produced from the AI-created prompt.
function Get-RuntimeCompatibilityReport {
[CmdletBinding()]
param(
# Each job supplies a name and the minimum PowerShell version it requires.
[Parameter(Mandatory)]
[psobject[]]$Job,
# The inventory is passed in explicitly so the function never inspects the host.
[Parameter(Mandatory)]
[version[]]$AvailableRuntime
)
# Normalize and sort the inventory once so selection is deterministic.
$runtimeInventory = @($AvailableRuntime | Sort-Object -Unique)
if ($runtimeInventory.Count -eq 0) {
throw 'At least one available runtime is required.'
}
foreach ($item in $Job) {
if ([string]::IsNullOrWhiteSpace([string]$item.Name)) {
throw 'Every job must have a name.'
}
# Convert the declared requirement to a real version for safe comparisons.
$minimumVersion = [version]$item.MinimumVersion
# Choose the oldest sufficient runtime to avoid demanding unnecessary upgrades.
$selected = $runtimeInventory |
Where-Object { $_ -ge $minimumVersion } |
Select-Object -First 1
# Explain both successful matches and gaps in plain language.
if ($null -ne $selected) {
$status = 'Ready'
$reason = "PowerShell $selected meets minimum $minimumVersion."
}
else {
$status = 'Upgrade Required'
$reason = "No available runtime meets minimum $minimumVersion."
}
# Emit structured output suitable for sorting, exporting, or CI policy checks.
[pscustomobject]@{
Job = [string]$item.Name
MinimumVersion = $minimumVersion.ToString()
SelectedRuntime = if ($selected) { $selected.ToString() } else { $null }
Status = $status
Reason = $reason
}
}
}
4. What Happened When It Ran
The actual captured output, errors, and exit status.
three jobs selected the lowest sufficient runtime and one job reported Upgrade Required; focused assertions verified both status paths.
Safety
fictional runtime inventory passed as in-memory data; the script did not inspect or change the host and used no network, file writes, deletion, registry/system changes, credentials, or arbitrary code execution.
Lab · 2026-09-19
Data Transfer Time Estimator
Estimate how long fictional data transfers take after accounting for usable bandwidth.
Validated
PowerShell 7 implementation
1. The Prompt AI Created for This Idea
After finding the scenario, AI turned it into this concise prompt. That prompt was then used to generate the PowerShell.
Create a PowerShell 7 function that estimates transfer time for objects with a name and decimal size in GB. Accept bandwidth in Mbps and an efficiency percentage, then return effective speed, seconds, and a readable duration. Validate inputs, use decimal calculations, and perform no network or file operations.
2. The Runner AI Created
AI also created run.ps1. It prepares the sample data, passes the parameters, and invokes the generated PowerShell.
#Requires -Version 7.0
# Load the AI-generated estimator from the neighboring solution file.
. "$PSScriptRoot/solution.ps1"
# Create fictional transfer requests entirely in memory.
$transfers = @(
[pscustomobject]@{ Name = 'Training archive'; SizeGB = 12.5 }
[pscustomobject]@{ Name = 'Photo library'; SizeGB = 48.0 }
[pscustomobject]@{ Name = 'Daily snapshot'; SizeGB = 3.25 }
)
# Estimate durations on a 200 Mbps link operating at 85 percent efficiency.
$transfers |
Get-DataTransferEstimate -BandwidthMbps 200 -EfficiencyPercent 85 |
Format-Table -AutoSize
3. The PowerShell AI Generated
solution.ps1 is the runnable PowerShell produced from the AI-created prompt.
#Requires -Version 7.0
function Get-DataTransferEstimate {
<#
.SYNOPSIS
Estimates transfer durations from data size and usable network throughput.
#>
[CmdletBinding()]
param(
# Objects must expose Name and SizeGB properties.
[Parameter(Mandatory, ValueFromPipeline)]
[object[]] $Transfer,
# Nominal link speed in megabits per second.
[Parameter(Mandatory)]
[ValidateRange(0.01, 1000000)]
[decimal] $BandwidthMbps,
# Percentage of nominal bandwidth expected to carry payload data.
[ValidateRange(1, 100)]
[decimal] $EfficiencyPercent = 85
)
begin {
# Convert the efficiency percentage into a multiplier once.
$efficiency = $EfficiencyPercent / 100
$effectiveMbps = $BandwidthMbps * $efficiency
}
process {
foreach ($item in $Transfer) {
# Validate each transfer independently so invalid sizes are identified clearly.
$sizeGB = [decimal]$item.SizeGB
if ($sizeGB -lt 0) {
throw "Transfer '$($item.Name)' has a negative SizeGB value."
}
# Decimal gigabytes contain eight billion bits; Mbps is one million bits per second.
$totalBits = $sizeGB * 8000000000
$bitsPerSecond = $effectiveMbps * 1000000
$seconds = if ($sizeGB -eq 0) { [decimal]0 } else { $totalBits / $bitsPerSecond }
# Convert the rounded seconds to a TimeSpan for a compact readable duration.
$roundedSeconds = [math]::Round([double]$seconds, 2)
$duration = [timespan]::FromSeconds([math]::Round([double]$seconds))
# Emit structured data so callers can format or export it as needed.
[pscustomobject][ordered]@{
Name = [string]$item.Name
SizeGB = $sizeGB
EffectiveMbps = [math]::Round([double]$effectiveMbps, 2)
EstimatedSeconds = $roundedSeconds
EstimatedDuration = $duration.ToString('hh\:mm\:ss')
}
}
}
}
4. What Happened When It Ran
The actual captured output, errors, and exit status.
three estimates used 170 Mbps effective throughput; focused assertions verified zero-size handling and the exact one-gigabyte result.
Safety
fictional in-memory values only; no network, file writes, deletion, registry/system changes, credential access, or arbitrary code execution.
Lab · 2026-09-19
Team Hours Pivot Workbook
Summarize fictional work logs by team and work type with an Excel pivot table and chart.
Validated
PowerShell 7 implementation
1. The Prompt AI Created for This Idea
After finding the scenario, AI turned it into this concise prompt. That prompt was then used to generate the PowerShell.
Create a PowerShell 7 function using ImportExcel that writes fictional work logs to an Excel table and adds a pivot table plus clustered-column pivot chart. Summarize hours by team and work type, freeze the source header, return workbook metadata, and write only to a caller-supplied `.xlsx` path.
2. The Runner AI Created
AI also created run.ps1. It prepares the sample data, passes the parameters, and invokes the generated PowerShell.
#Requires -Version 7.0
# Load the AI-generated workbook function.
. "$PSScriptRoot/solution.ps1"
# Prepare fictional work logs with several teams and work categories.
$workLogs = @(
[pscustomobject]@{ Date = '2026-09-14'; Team = 'Atlas'; WorkType = 'Build'; Hours = 6.5 }
[pscustomobject]@{ Date = '2026-09-14'; Team = 'Atlas'; WorkType = 'Support'; Hours = 2.0 }
[pscustomobject]@{ Date = '2026-09-15'; Team = 'Beacon'; WorkType = 'Build'; Hours = 5.0 }
[pscustomobject]@{ Date = '2026-09-15'; Team = 'Beacon'; WorkType = 'Research'; Hours = 3.5 }
[pscustomobject]@{ Date = '2026-09-16'; Team = 'Cygnus'; WorkType = 'Support'; Hours = 4.0 }
[pscustomobject]@{ Date = '2026-09-16'; Team = 'Cygnus'; WorkType = 'Research'; Hours = 4.5 }
)
# Use a unique temporary path so the run never overwrites another workbook.
$workbookPath = Join-Path ([System.IO.Path]::GetTempPath()) "team-hours-$([guid]::NewGuid().ToString('N')).xlsx"
# Build the workbook and independently read the source rows back from disk.
$summary = New-TeamHoursPivotWorkbook -WorkLog $workLogs -Path $workbookPath
$readBack = Import-Excel -Path $workbookPath -WorksheetName 'Work Log'
# Display both the workbook metadata and read-back team totals.
$summary | Format-List
$readBack | Group-Object Team | Sort-Object Name | Select-Object Name, Count | Format-Table -AutoSize
3. The PowerShell AI Generated
solution.ps1 is the runnable PowerShell produced from the AI-created prompt.
#Requires -Version 7.0
function New-TeamHoursPivotWorkbook {
<#
.SYNOPSIS
Builds a work-log workbook with a pivot summary and chart.
#>
[CmdletBinding()]
param(
# Work-log rows must expose Date, Team, WorkType, and Hours.
[Parameter(Mandatory)]
[object[]] $WorkLog,
# Destination for the generated workbook.
[Parameter(Mandatory)]
[ValidatePattern('\.xlsx$')]
[string] $Path
)
# Load ImportExcel while suppressing only its platform-specific autosize warning.
$savedWarningPreference = $global:WarningPreference
try {
$global:WarningPreference = 'SilentlyContinue'
Import-Module ImportExcel -ErrorAction Stop
}
finally {
$global:WarningPreference = $savedWarningPreference
}
# Normalize the supplied records into a stable shape for Excel and the pivot cache.
$rows = foreach ($item in $WorkLog) {
$hours = [double]$item.Hours
if ($hours -lt 0) {
throw 'Hours cannot be negative.'
}
[pscustomobject][ordered]@{
Date = [datetime]$item.Date
Team = [string]$item.Team
WorkType = [string]$item.WorkType
Hours = $hours
}
}
# Export the source table and create a pivot table with a clustered-column chart.
$package = $rows | Export-Excel -Path $Path -WorksheetName 'Work Log' `
-TableName 'TeamWorkLog' -TableStyle Medium6 -FreezeTopRow `
-IncludePivotTable -PivotTableName 'TeamHoursPivot' `
-PivotRows 'Team' -PivotColumns 'WorkType' -PivotData @{ Hours = 'Sum' } `
-IncludePivotChart -PivotChartType ColumnClustered -PassThru
# Apply predictable source-column widths without platform drawing dependencies.
$sourceSheet = $package.Workbook.Worksheets['Work Log']
$sourceSheet.Column(1).Width = 14
$sourceSheet.Column(2).Width = 18
$sourceSheet.Column(3).Width = 18
$sourceSheet.Column(4).Width = 12
# Collect metadata before closing and saving the package.
$pivotCount = @($package.Workbook.Worksheets | ForEach-Object { $_.PivotTables.Count } | Measure-Object -Sum).Sum
$chartCount = @($package.Workbook.Worksheets | ForEach-Object { $_.Drawings.Count } | Measure-Object -Sum).Sum
$worksheetCount = $package.Workbook.Worksheets.Count
Close-ExcelPackage -ExcelPackage $package
# Return a concise summary for logging and validation.
[pscustomobject][ordered]@{
Workbook = $Path
Rows = $rows.Count
Teams = @($rows.Team | Sort-Object -Unique).Count
Worksheets = $worksheetCount
PivotTables = $pivotCount
Charts = $chartCount
}
}
4. What Happened When It Ran
The actual captured output, errors, and exit status.
six source rows were read back; the saved workbook contained two worksheets, one pivot table, and one pivot chart; focused assertions independently reopened and inspected another workbook.
Safety
fictional records only; the script writes one uniquely named workbook under the temporary directory and performs no network access, deletion, registry/system changes, credential access, or arbitrary code execution.
Lab · 2026-09-19
Activity Session Builder
Group timestamped events into sessions whenever an idle gap crosses a threshold.
Validated
PowerShell 7 implementation
1. The Prompt AI Created for This Idea
After finding the scenario, AI turned it into this concise prompt. That prompt was then used to generate the PowerShell.
Create a PowerShell 7 function that sorts timestamped activity records and assigns session numbers. Start a new session when the gap from the previous event exceeds a caller-supplied idle threshold. Return event, timestamp, session, and gap minutes; use in-memory data only.
2. The Runner AI Created
AI also created run.ps1. It prepares the sample data, passes the parameters, and invokes the generated PowerShell.
solution.ps1 is the runnable PowerShell produced from the AI-created prompt.
#Requires -Version 7.0
function Group-ActivitySession {
<#
.SYNOPSIS
Assigns chronological activity records to idle-gap sessions.
#>
[CmdletBinding()]
param(
# Activity objects must expose Event and Timestamp properties.
[Parameter(Mandatory)]
[object[]] $Activity,
# A larger gap starts a new session.
[ValidateRange(1, 1440)]
[int] $IdleMinutes = 30
)
# Normalize and sort the events so out-of-order input is handled consistently.
$ordered = @($Activity | ForEach-Object {
[pscustomobject][ordered]@{
Event = [string]$_.Event
Timestamp = [datetime]$_.Timestamp
}
} | Sort-Object Timestamp)
# Start numbering at one when the first event is encountered.
$session = 0
$previousTimestamp = $null
foreach ($item in $ordered) {
# The first event has no gap; later events measure from the previous timestamp.
$gapMinutes = if ($null -eq $previousTimestamp) {
$null
}
else {
[math]::Round(($item.Timestamp - $previousTimestamp).TotalMinutes, 2)
}
# Begin a session for the first event or after a gap beyond the threshold.
if ($session -eq 0 -or $gapMinutes -gt $IdleMinutes) {
$session++
}
# Emit one structured row for each activity.
[pscustomobject][ordered]@{
Event = $item.Event
Timestamp = $item.Timestamp
Session = $session
MinutesSincePrior = $gapMinutes
}
$previousTimestamp = $item.Timestamp
}
}
4. What Happened When It Ran
The actual captured output, errors, and exit status.
out-of-order input was sorted into three sessions; focused assertions verified that an exact-threshold gap stays in the session while a larger gap starts another.
Safety
fictional in-memory events only; no network, file writes, deletion, registry/system changes, credential access, or arbitrary code execution.
Lab · 2026-09-19
Configuration Precedence Resolver
Combine layered settings while showing which source supplied every final value.
Validated
PowerShell 7 implementation
1. The Prompt AI Created for This Idea
After finding the scenario, AI turned it into this concise prompt. That prompt was then used to generate the PowerShell.
Create a PowerShell 7 function that resolves default, environment, and user configuration dictionaries. User values override environment values, which override defaults. Return each key, final value, and winning source while preserving first-seen key order. Use in-memory data only.
2. The Runner AI Created
AI also created run.ps1. It prepares the sample data, passes the parameters, and invokes the generated PowerShell.
#Requires -Version 7.0
# Load the AI-generated configuration resolver.
. "$PSScriptRoot/solution.ps1"
# Define fictional settings at three precedence levels.
$defaults = [ordered]@{
Theme = 'Light'
PageSize = 25
RetryCount = 2
}
$environment = [ordered]@{
PageSize = 50
Region = 'East'
}
$user = [ordered]@{
Theme = 'Dark'
RetryCount = 4
}
# Resolve the final values and retain their winning source.
Resolve-ConfigurationPrecedence -Defaults $defaults -Environment $environment -User $user |
Format-Table -AutoSize
3. The PowerShell AI Generated
solution.ps1 is the runnable PowerShell produced from the AI-created prompt.
#Requires -Version 7.0
function Resolve-ConfigurationPrecedence {
<#
.SYNOPSIS
Resolves layered configuration and reports the source of each winning value.
#>
[CmdletBinding()]
param(
# Baseline values used when no higher layer supplies the key.
[Parameter(Mandatory)]
[System.Collections.IDictionary] $Defaults,
# Environment-specific overrides.
[Parameter(Mandatory)]
[System.Collections.IDictionary] $Environment,
# Highest-precedence user overrides.
[Parameter(Mandatory)]
[System.Collections.IDictionary] $User
)
# Capture keys in first-seen order while preventing duplicates.
$keys = [System.Collections.Generic.List[string]]::new()
$seen = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase)
foreach ($layer in @($Defaults, $Environment, $User)) {
foreach ($key in $layer.Keys) {
if ($seen.Add([string]$key)) {
$keys.Add([string]$key)
}
}
}
foreach ($key in $keys) {
# Check layers from highest to lowest precedence.
if ($User.Contains($key)) {
$value = $User[$key]
$source = 'User'
}
elseif ($Environment.Contains($key)) {
$value = $Environment[$key]
$source = 'Environment'
}
else {
$value = $Defaults[$key]
$source = 'Defaults'
}
# Emit provenance with each resolved setting.
[pscustomobject][ordered]@{
Key = $key
Value = $value
Source = $source
}
}
}
4. What Happened When It Ran
The actual captured output, errors, and exit status.
PowerShell version: 7.6.6
Command: pwsh -NoLogo -NoProfile -NonInteractive -File ./run.ps1
Exit status: 0
STDOUT:
Key Value Source
--- ----- ------
Theme Dark User
PageSize 50 Environment
RetryCount 4 User
Region East Environment
STDERR:
(empty)
5. Validation Performed by the AI Workflow
The runtime, expected results, and safety boundaries were checked and recorded.
four keys were resolved with the expected winning layers; focused assertions verified first-seen order and both user and environment precedence.
Safety
fictional in-memory dictionaries only; no network, file writes, deletion, registry/system changes, credential access, or arbitrary code execution.
Lab · 2026-09-19
Balanced Work Queue Allocator
Assign work items by repeatedly choosing the worker with the lightest current load.
Validated
PowerShell 7 implementation
1. The Prompt AI Created for This Idea
After finding the scenario, AI turned it into this concise prompt. That prompt was then used to generate the PowerShell.
Create a PowerShell 7 function that assigns named work items with estimated minutes to a supplied worker list. Process longest items first, always choose the least-loaded worker, break ties by worker order, and return each assignment with the worker's running total. Validate inputs and use in-memory data only.
2. The Runner AI Created
AI also created run.ps1. It prepares the sample data, passes the parameters, and invokes the generated PowerShell.
#Requires -Version 7.0
# Load the AI-generated allocator.
. "$PSScriptRoot/solution.ps1"
# Create fictional work items with varied effort estimates.
$items = @(
[pscustomobject]@{ Name = 'Prepare demo'; EstimatedMinutes = 80 }
[pscustomobject]@{ Name = 'Review notes'; EstimatedMinutes = 25 }
[pscustomobject]@{ Name = 'Build sample'; EstimatedMinutes = 65 }
[pscustomobject]@{ Name = 'Check output'; EstimatedMinutes = 35 }
[pscustomobject]@{ Name = 'Write summary'; EstimatedMinutes = 45 }
[pscustomobject]@{ Name = 'Package files'; EstimatedMinutes = 20 }
)
# Allocate the queue across three fictional workers.
Get-BalancedWorkAllocation -WorkItem $items -Worker @('Avery', 'Blake', 'Casey') |
Format-Table -AutoSize
3. The PowerShell AI Generated
solution.ps1 is the runnable PowerShell produced from the AI-created prompt.
#Requires -Version 7.0
function Get-BalancedWorkAllocation {
<#
.SYNOPSIS
Assigns estimated work to the currently least-loaded worker.
#>
[CmdletBinding()]
param(
# Work items must expose Name and EstimatedMinutes properties.
[Parameter(Mandatory)]
[object[]] $WorkItem,
# Worker names are used in the supplied order to resolve load ties.
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string[]] $Worker
)
# Worker names must be unique so assignments remain unambiguous.
if (($Worker | Sort-Object -Unique).Count -ne $Worker.Count) {
throw 'Worker names must be unique.'
}
# Track each worker's running load and original tie-break position.
$loads = for ($index = 0; $index -lt $Worker.Count; $index++) {
[pscustomobject]@{
Worker = $Worker[$index]
TotalMinutes = 0
Order = $index
}
}
# Normalize estimates and process the longest items first for better balance.
$orderedItems = @($WorkItem | ForEach-Object {
$minutes = [int]$_.EstimatedMinutes
if ($minutes -lt 0) {
throw "Work item '$($_.Name)' has a negative estimate."
}
[pscustomobject]@{
Name = [string]$_.Name
EstimatedMinutes = $minutes
}
} | Sort-Object @{ Expression = 'EstimatedMinutes'; Descending = $true }, Name)
foreach ($item in $orderedItems) {
# Choose the lightest worker, using original worker order for ties.
$target = $loads | Sort-Object TotalMinutes, Order | Select-Object -First 1
$target.TotalMinutes += $item.EstimatedMinutes
# Emit the decision and the worker's new running total.
[pscustomobject][ordered]@{
WorkItem = $item.Name
EstimatedMinutes = $item.EstimatedMinutes
Worker = $target.Worker
WorkerTotalMinutes = $target.TotalMinutes
}
}
}
4. What Happened When It Ran
The actual captured output, errors, and exit status.
six items were assigned once with final loads of 100, 90, and 80 minutes; focused assertions verified stable tie-breaking and duplicate-worker rejection.
Safety
fictional in-memory work items only; no network, file writes, deletion, registry/system changes, credential access, or arbitrary code execution.
Lab · 2026-09-18
Nested Object Property Map
Turn a nested object into a readable path-and-value inventory.
Validated
PowerShell 7 implementation
1. The Prompt AI Created for This Idea
After finding the scenario, AI turned it into this concise prompt. That prompt was then used to generate the PowerShell.
Create a PowerShell 7 function that flattens a nested object into `Path`, `Type`, and `Value` rows. Accept an object and maximum depth, preserve property order, handle arrays, and report deeper values as truncated. Use in-memory data only and do not modify the input.
2. The Runner AI Created
AI also created run.ps1. It prepares the sample data, passes the parameters, and invokes the generated PowerShell.
#Requires -Version 7.0
# Load the AI-generated function from the neighboring solution file.
. "$PSScriptRoot/solution.ps1"
# Create a fictional nested service profile entirely in memory.
$serviceProfile = [pscustomobject][ordered]@{
Name = 'Northwind Alerts'
Enabled = $true
Owners = @('Mina', 'Luis')
Routing = [pscustomobject][ordered]@{
Region = 'East'
Channels = @(
[pscustomobject]@{ Name = 'Email'; Priority = 1 }
[pscustomobject]@{ Name = 'Chat'; Priority = 2 }
)
}
}
# Pass the object and depth boundary into the generated solution.
Get-ObjectPropertyMap -InputObject $serviceProfile -MaxDepth 5 |
Format-Table -AutoSize
3. The PowerShell AI Generated
solution.ps1 is the runnable PowerShell produced from the AI-created prompt.
#Requires -Version 7.0
function Get-ObjectPropertyMap {
<#
.SYNOPSIS
Flattens a nested object into inspectable path, type, and value rows.
#>
[CmdletBinding()]
param(
# The object whose properties will be inspected.
[Parameter(Mandatory, ValueFromPipeline)]
[AllowNull()]
[object] $InputObject,
# The deepest level that will be expanded.
[ValidateRange(0, 20)]
[int] $MaxDepth = 4
)
begin {
# Keep a reference-based set so a circular object graph cannot recurse forever.
$visited = [System.Collections.Generic.HashSet[int]]::new()
# Recursively inspect a value and emit one row for each leaf or boundary.
function Expand-Value {
param(
[AllowNull()][object] $Value,
[string] $Path,
[int] $Depth
)
# Represent null explicitly because it has no runtime type.
if ($null -eq $Value) {
[pscustomobject]@{ Path = $Path; Type = 'null'; Value = '<null>' }
return
}
# Treat common scalar types as leaves rather than expanding their properties.
$isScalar = $Value -is [string] -or
$Value -is [ValueType] -or
$Value -is [datetime]
if ($isScalar) {
[pscustomobject]@{ Path = $Path; Type = $Value.GetType().Name; Value = [string]$Value }
return
}
# Stop expansion at the requested boundary and clearly label the row.
if ($Depth -ge $MaxDepth) {
[pscustomobject]@{ Path = $Path; Type = $Value.GetType().Name; Value = '<max depth>' }
return
}
# Use the runtime identity hash to detect repeated reference objects.
$identity = [System.Runtime.CompilerServices.RuntimeHelpers]::GetHashCode($Value)
if (-not $visited.Add($identity)) {
[pscustomobject]@{ Path = $Path; Type = $Value.GetType().Name; Value = '<already visited>' }
return
}
# Expand enumerable values by their zero-based positions.
if ($Value -is [System.Collections.IEnumerable] -and $Value -isnot [System.Collections.IDictionary]) {
$index = 0
foreach ($item in $Value) {
Expand-Value -Value $item -Path "$Path[$index]" -Depth ($Depth + 1)
$index++
}
return
}
# Expand dictionary keys in their enumeration order.
if ($Value -is [System.Collections.IDictionary]) {
foreach ($key in $Value.Keys) {
Expand-Value -Value $Value[$key] -Path "$Path.$key" -Depth ($Depth + 1)
}
return
}
# Expand PowerShell object properties in the order exposed by PSObject.
foreach ($property in $Value.PSObject.Properties) {
Expand-Value -Value $property.Value -Path "$Path.$($property.Name)" -Depth ($Depth + 1)
}
}
}
process {
# Begin every input object at a stable root path.
Expand-Value -Value $InputObject -Path '$' -Depth 0
}
}
4. What Happened When It Ran
The actual captured output, errors, and exit status.
PowerShell version: 7.6.6
Command: pwsh -NoLogo -NoProfile -NonInteractive -File ./run.ps1
Exit status: 0
STDOUT:
Path Type Value
---- ---- -----
$.Name String Northwind Alerts
$.Enabled Boolean True
$.Owners[0] String Mina
$.Owners[1] String Luis
$.Routing.Region String East
$.Routing.Channels[0].Name String Email
$.Routing.Channels[0].Priority Int32 1
$.Routing.Channels[1].Name String Chat
$.Routing.Channels[1].Priority Int32 2
STDERR:
(empty)
5. Validation Performed by the AI Workflow
The runtime, expected results, and safety boundaries were checked and recorded.
ordered scalar and array paths were emitted; focused assertions confirmed nested paths and leaf values.
Safety
fictional in-memory data only; no network, file writes, deletion, registry/system changes, credential access, or arbitrary code execution.
Lab · 2026-09-18
SLA Breach Workbook
Create a formatted Excel review that makes breached service targets stand out.
Validated
PowerShell 7 implementation
1. The Prompt AI Created for This Idea
After finding the scenario, AI turned it into this concise prompt. That prompt was then used to generate the PowerShell.
Create a PowerShell 7 script using ImportExcel that exports fictional support tickets to a formatted workbook. Calculate remaining SLA hours and breach status, freeze the header, add a table, and highlight breached rows. Return a summary object and write only to a caller-supplied path.
2. The Runner AI Created
AI also created run.ps1. It prepares the sample data, passes the parameters, and invokes the generated PowerShell.
#Requires -Version 7.0
# Load the AI-generated workbook function.
. "$PSScriptRoot/solution.ps1"
# Prepare fictional ticket data with both healthy and breached examples.
$tickets = @(
[pscustomobject]@{ Ticket = 'SR-1042'; Team = 'Identity'; Priority = 'High'; AgeHours = 5; SlaHours = 8 }
[pscustomobject]@{ Ticket = 'SR-1043'; Team = 'Network'; Priority = 'Medium'; AgeHours = 29; SlaHours = 24 }
[pscustomobject]@{ Ticket = 'SR-1044'; Team = 'Apps'; Priority = 'Low'; AgeHours = 16; SlaHours = 48 }
[pscustomobject]@{ Ticket = 'SR-1045'; Team = 'Identity'; Priority = 'High'; AgeHours = 11; SlaHours = 8 }
)
# Use a unique temporary path so the run never overwrites another workbook.
$workbookPath = Join-Path ([System.IO.Path]::GetTempPath()) "sla-review-$([guid]::NewGuid().ToString('N')).xlsx"
# Create the workbook, then independently read it back to verify the contents.
$summary = New-SlaBreachWorkbook -Ticket $tickets -Path $workbookPath
$importedRows = Import-Excel -Path $workbookPath -WorksheetName 'SLA Review'
# Show the generated summary and a read-back status count.
$summary | Format-List
$importedRows | Group-Object Status | Sort-Object Name | Select-Object Name, Count | Format-Table -AutoSize
3. The PowerShell AI Generated
solution.ps1 is the runnable PowerShell produced from the AI-created prompt.
#Requires -Version 7.0
function New-SlaBreachWorkbook {
<#
.SYNOPSIS
Creates a formatted SLA review workbook from supplied ticket records.
#>
[CmdletBinding()]
param(
# Fictional ticket records containing Ticket, Team, Priority, AgeHours, and SlaHours.
[Parameter(Mandatory)]
[object[]] $Ticket,
# Destination for the generated .xlsx workbook.
[Parameter(Mandatory)]
[ValidatePattern('\.xlsx$')]
[string] $Path
)
# Stop immediately if the required module cannot be loaded.
$savedWarningPreference = $global:WarningPreference
try {
$global:WarningPreference = 'SilentlyContinue'
Import-Module ImportExcel -ErrorAction Stop -WarningAction SilentlyContinue
}
finally {
$global:WarningPreference = $savedWarningPreference
}
# Transform the source records into a stable, workbook-friendly shape.
$rows = foreach ($item in $Ticket) {
$remaining = [double]$item.SlaHours - [double]$item.AgeHours
[pscustomobject][ordered]@{
Ticket = [string]$item.Ticket
Team = [string]$item.Team
Priority = [string]$item.Priority
AgeHours = [double]$item.AgeHours
SlaHours = [double]$item.SlaHours
RemainingHours = $remaining
Status = if ($remaining -lt 0) { 'Breached' } else { 'Within SLA' }
}
}
# Export the rows and retain the package so worksheet styling can be applied.
$package = $rows | Export-Excel -Path $Path -WorksheetName 'SLA Review' `
-TableName 'SlaReview' -TableStyle Medium2 -FreezeTopRow -PassThru
# Retrieve the newly created worksheet from the in-memory package.
$worksheet = $package.Workbook.Worksheets['SLA Review']
# Apply predictable column widths without relying on platform drawing libraries.
foreach ($columnNumber in 1..7) {
$worksheet.Column($columnNumber).Width = if ($columnNumber -eq 2) { 18 } else { 14 }
}
# Highlight breached status cells so urgent rows are easy to spot.
if ($rows.Count -gt 0) {
Add-ConditionalFormatting -Worksheet $worksheet -Address "G2:G$($rows.Count + 1)" `
-RuleType Equal -ConditionValue '"Breached"' -BackgroundColor LightPink -ForegroundColor DarkRed
}
# Save and close the workbook package cleanly.
Close-ExcelPackage -ExcelPackage $package
# Return a concise object that is convenient for logging and validation.
[pscustomobject][ordered]@{
Workbook = $Path
Tickets = $rows.Count
Breached = @($rows | Where-Object Status -eq 'Breached').Count
WithinSla = @($rows | Where-Object Status -eq 'Within SLA').Count
}
}
4. What Happened When It Ran
The actual captured output, errors, and exit status.
four rows were read back from the workbook, the two status counts matched, and focused assertions verified the table, conditional-format rule, and worksheet dimensions.
Safety
fictional records only; the script writes one uniquely named workbook under the temporary directory and performs no network access, deletion, registry/system changes, credential access, or arbitrary code execution.
Lab · 2026-09-18
Retry Backoff Schedule
Preview a capped exponential retry plan without waiting or calling a service.
Validated
PowerShell 7 implementation
1. The Prompt AI Created for This Idea
After finding the scenario, AI turned it into this concise prompt. That prompt was then used to generate the PowerShell.
Create a PowerShell 7 function that previews a deterministic exponential retry schedule. Accept attempt count, initial delay, multiplier, and maximum delay; return attempt, delay, and cumulative elapsed seconds. Validate inputs and do not sleep or perform network activity.
2. The Runner AI Created
AI also created run.ps1. It prepares the sample data, passes the parameters, and invokes the generated PowerShell.
#Requires -Version 7.0
# Load the AI-generated schedule function.
. "$PSScriptRoot/solution.ps1"
# Preview six retries with a short initial delay and a five-second cap.
Get-RetryBackoffSchedule -Attempts 6 -InitialDelaySeconds 0.5 -Multiplier 2 -MaximumDelaySeconds 5 |
Format-Table -AutoSize
3. The PowerShell AI Generated
solution.ps1 is the runnable PowerShell produced from the AI-created prompt.
#Requires -Version 7.0
function Get-RetryBackoffSchedule {
<#
.SYNOPSIS
Calculates a capped exponential retry schedule without waiting.
#>
[CmdletBinding()]
param(
# Number of retry attempts to include.
[Parameter(Mandatory)]
[ValidateRange(1, 100)]
[int] $Attempts,
# Delay before the first retry, in seconds.
[ValidateRange(0.001, 86400)]
[double] $InitialDelaySeconds = 1,
# Factor applied to the delay after each attempt.
[ValidateRange(1, 10)]
[double] $Multiplier = 2,
# Upper boundary for any single delay.
[ValidateRange(0.001, 86400)]
[double] $MaximumDelaySeconds = 30
)
# The cap must not be smaller than the first requested delay.
if ($MaximumDelaySeconds -lt $InitialDelaySeconds) {
throw 'MaximumDelaySeconds must be greater than or equal to InitialDelaySeconds.'
}
# Track cumulative time so callers can assess the complete retry budget.
$elapsed = 0.0
foreach ($attempt in 1..$Attempts) {
# Grow exponentially, then enforce the configured maximum.
$uncapped = $InitialDelaySeconds * [math]::Pow($Multiplier, $attempt - 1)
$delay = [math]::Min($uncapped, $MaximumDelaySeconds)
$elapsed += $delay
# Emit numeric values rounded for stable display and downstream use.
[pscustomobject][ordered]@{
Attempt = $attempt
DelaySeconds = [math]::Round($delay, 3)
TotalElapsedSeconds = [math]::Round($elapsed, 3)
Capped = $uncapped -gt $MaximumDelaySeconds
}
}
}
4. What Happened When It Ran
The actual captured output, errors, and exit status.
six attempts were produced, the five-second cap was enforced, and focused assertions verified delay and cumulative totals.
Safety
deterministic calculations only; the script does not sleep, use the network, write files, modify the system, access credentials, or execute arbitrary code.
Lab · 2026-09-18
Dependency Wave Planner
Arrange dependent work into safe waves that expose parallel opportunities.
Validated
PowerShell 7 implementation
1. The Prompt AI Created for This Idea
After finding the scenario, AI turned it into this concise prompt. That prompt was then used to generate the PowerShell.
Create a PowerShell 7 function that groups tasks into execution waves from their names and dependencies. Tasks in the same wave may run in parallel. Reject duplicate names, missing dependencies, and cycles; preserve input order within each wave. Use in-memory objects only.
2. The Runner AI Created
AI also created run.ps1. It prepares the sample data, passes the parameters, and invokes the generated PowerShell.
#Requires -Version 7.0
# Load the AI-generated dependency planner.
. "$PSScriptRoot/solution.ps1"
# Describe a fictional release process with parallel-friendly dependencies.
$tasks = @(
[pscustomobject]@{ Name = 'Package'; DependsOn = @('Test') }
[pscustomobject]@{ Name = 'Lint'; DependsOn = @() }
[pscustomobject]@{ Name = 'Publish docs'; DependsOn = @('Test') }
[pscustomobject]@{ Name = 'Test'; DependsOn = @('Lint', 'Compile') }
[pscustomobject]@{ Name = 'Compile'; DependsOn = @() }
[pscustomobject]@{ Name = 'Release'; DependsOn = @('Package', 'Publish docs') }
)
# Plan the waves and display the parameters represented by the sample tasks.
Get-DependencyWave -Task $tasks | Format-Table -AutoSize
3. The PowerShell AI Generated
solution.ps1 is the runnable PowerShell produced from the AI-created prompt.
#Requires -Version 7.0
function Get-DependencyWave {
<#
.SYNOPSIS
Groups dependency-linked tasks into safe execution waves.
#>
[CmdletBinding()]
param(
# Task objects must expose Name and DependsOn properties.
[Parameter(Mandatory)]
[object[]] $Task
)
# Build an ordered lookup while detecting duplicate task names.
$byName = [ordered]@{}
foreach ($item in $Task) {
$name = [string]$item.Name
if ([string]::IsNullOrWhiteSpace($name)) {
throw 'Every task must have a non-empty Name.'
}
if ($byName.Contains($name)) {
throw "Duplicate task name: $name"
}
$byName[$name] = $item
}
# Validate every dependency before planning any waves.
foreach ($item in $Task) {
foreach ($dependency in @($item.DependsOn)) {
if (-not $byName.Contains([string]$dependency)) {
throw "Task '$($item.Name)' references missing dependency '$dependency'."
}
}
}
# Track completed names and unresolved tasks separately.
$completed = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase)
$remaining = [System.Collections.Generic.List[object]]::new()
foreach ($item in $Task) { $remaining.Add($item) }
$waveNumber = 1
while ($remaining.Count -gt 0) {
# A task is ready only when all of its dependencies are complete.
$ready = @($remaining | Where-Object {
$dependencies = @($_.DependsOn)
@($dependencies | Where-Object { -not $completed.Contains([string]$_) }).Count -eq 0
})
# No ready tasks means the unresolved portion contains a cycle.
if ($ready.Count -eq 0) {
$blocked = ($remaining.Name -join ', ')
throw "Dependency cycle detected among: $blocked"
}
# Emit tasks in their original order with useful planning metadata.
foreach ($item in $ready) {
[pscustomobject][ordered]@{
Wave = $waveNumber
Task = [string]$item.Name
DependsOn = (@($item.DependsOn) -join ', ')
}
[void]$completed.Add([string]$item.Name)
[void]$remaining.Remove($item)
}
$waveNumber++
}
}
4. What Happened When It Ran
The actual captured output, errors, and exit status.
all six tasks appeared once, dependency order was respected, and focused assertions verified ordering plus cycle detection.
Safety
fictional in-memory task data only; no network, file writes, deletion, registry/system changes, credential access, or arbitrary code execution.
Lab · 2026-09-18
Maintenance Window Overlap Report
Find every conflict among fictional maintenance windows.
Validated
PowerShell 7 implementation
1. The Prompt AI Created for This Idea
After finding the scenario, AI turned it into this concise prompt. That prompt was then used to generate the PowerShell.
Create a PowerShell 7 function that finds overlaps among named maintenance windows with start and end times. Validate each range, compare every pair, and return both names plus overlap start, end, and minutes. Treat touching boundaries as non-overlapping and use in-memory data only.
2. The Runner AI Created
AI also created run.ps1. It prepares the sample data, passes the parameters, and invokes the generated PowerShell.
#Requires -Version 7.0
# Load the AI-generated overlap finder.
. "$PSScriptRoot/solution.ps1"
# Create deterministic fictional windows in one local time zone.
$windows = @(
[pscustomobject]@{ Name = 'Database patch'; Start = [datetime]'2026-10-03T22:00:00'; End = [datetime]'2026-10-03T23:30:00' }
[pscustomobject]@{ Name = 'Network upgrade'; Start = [datetime]'2026-10-03T23:00:00'; End = [datetime]'2026-10-04T00:00:00' }
[pscustomobject]@{ Name = 'Cache refresh'; Start = [datetime]'2026-10-03T22:45:00'; End = [datetime]'2026-10-03T23:10:00' }
[pscustomobject]@{ Name = 'Search reindex'; Start = [datetime]'2026-10-04T00:00:00'; End = [datetime]'2026-10-04T01:00:00' }
)
# Find and display every conflicting pair.
Find-MaintenanceWindowOverlap -Window $windows |
Format-Table First, Second, OverlapStart, OverlapEnd, OverlapMinutes -AutoSize |
Out-String -Width 180
3. The PowerShell AI Generated
solution.ps1 is the runnable PowerShell produced from the AI-created prompt.
#Requires -Version 7.0
function Find-MaintenanceWindowOverlap {
<#
.SYNOPSIS
Reports every overlapping pair of supplied maintenance windows.
#>
[CmdletBinding()]
param(
# Window objects must expose Name, Start, and End properties.
[Parameter(Mandatory)]
[object[]] $Window
)
# Normalize and validate every supplied range before comparison.
$normalized = foreach ($item in $Window) {
$start = [datetime]$item.Start
$end = [datetime]$item.End
if ($end -le $start) {
throw "Window '$($item.Name)' must end after it starts."
}
[pscustomobject][ordered]@{
Name = [string]$item.Name
Start = $start
End = $end
}
}
# Compare each unique pair exactly once.
for ($leftIndex = 0; $leftIndex -lt $normalized.Count; $leftIndex++) {
for ($rightIndex = $leftIndex + 1; $rightIndex -lt $normalized.Count; $rightIndex++) {
$left = $normalized[$leftIndex]
$right = $normalized[$rightIndex]
# The intersection starts later and ends earlier than its inputs.
$overlapStart = if ($left.Start -gt $right.Start) { $left.Start } else { $right.Start }
$overlapEnd = if ($left.End -lt $right.End) { $left.End } else { $right.End }
# Strict comparison makes touching boundaries non-overlapping.
if ($overlapStart -lt $overlapEnd) {
[pscustomobject][ordered]@{
First = $left.Name
Second = $right.Name
OverlapStart = $overlapStart
OverlapEnd = $overlapEnd
OverlapMinutes = [math]::Round(($overlapEnd - $overlapStart).TotalMinutes, 1)
}
}
}
}
}
4. What Happened When It Ran
The actual captured output, errors, and exit status.
three conflicting pairs and their intersection lengths were returned; focused assertions confirmed that touching boundaries are not conflicts.
Safety
fictional in-memory schedules only; no calendar access, network, file writes, deletion, registry/system changes, credential access, or arbitrary code execution.
Lab · 2026-09-17
Budget Variance Calculator
Compare fictional plan and actual amounts, then make the variance easy to scan.
Validated
PowerShell 7 implementation
1. The Prompt AI Created for This Idea
After finding the scenario, AI turned it into this concise prompt. That prompt was then used to generate the PowerShell.
Create a fully commented PowerShell 7 script that accepts fictional budget records, calculates actual-versus-plan variance and percentage, and returns a structured report plus totals. Use decimal arithmetic, in-memory data, and read-only processing; no files, network, credentials, registry, system changes, or arbitrary code.
2. The Runner AI Created
AI also created run.ps1. It prepares the sample data, passes the parameters, and invokes the generated PowerShell.
# Build fictional monthly budget records for a repeatable demonstration.
$sample = @(
[pscustomobject]@{ Category = 'Cloud'; Plan = 1200; Actual = 1345.50 }
[pscustomobject]@{ Category = 'Training'; Plan = 800; Actual = 640 }
[pscustomobject]@{ Category = 'Travel'; Plan = 500; Actual = 500 }
)
# Invoke the generated solution with the sample records.
& "$PSScriptRoot/solution.ps1" -Category $sample |
Format-Table Category, Plan, Actual, Variance, VariancePct, Direction -AutoSize
3. The PowerShell AI Generated
solution.ps1 is the runnable PowerShell produced from the AI-created prompt.
[CmdletBinding()]
param(
# Accept budget records from the pipeline or as an array.
[Parameter(Mandatory, ValueFromPipeline)]
[psobject[]]$Category
)
begin {
# Collect records so the report and totals can be emitted together.
$records = [System.Collections.Generic.List[psobject]]::new()
}
process {
# Add each incoming record to the in-memory collection.
foreach ($item in $Category) {
$records.Add($item)
}
}
end {
# Calculate one variance row for every category.
$rows = foreach ($item in $records) {
# Convert numeric values to decimal for predictable currency arithmetic.
$plan = [decimal]$item.Plan
$actual = [decimal]$item.Actual
$variance = $actual - $plan
# Avoid division by zero when a category has no planned amount.
$percent = if ($plan -eq 0) { $null } else { [math]::Round(($variance / $plan) * 100, 2) }
# Label the direction so the report is easy to scan.
$direction = if ($variance -gt 0) { 'Over plan' } elseif ($variance -lt 0) { 'Under plan' } else { 'On plan' }
# Return a structured object rather than a formatted string.
[pscustomobject]@{
Category = [string]$item.Category
Plan = $plan
Actual = $actual
Variance = $variance
VariancePct = $percent
Direction = $direction
}
}
# Emit detail rows in a stable category order.
$rows | Sort-Object Category
# Emit a separate total row for the complete sample.
$totalPlan = ($rows | Measure-Object -Property Plan -Sum).Sum
$totalActual = ($rows | Measure-Object -Property Actual -Sum).Sum
[pscustomobject]@{
Category = 'TOTAL'
Plan = [decimal]$totalPlan
Actual = [decimal]$totalActual
Variance = [decimal]($totalActual - $totalPlan)
VariancePct = if ($totalPlan -eq 0) { $null } else { [math]::Round((($totalActual - $totalPlan) / $totalPlan) * 100, 2) }
Direction = if ($totalActual -gt $totalPlan) { 'Over plan' } elseif ($totalActual -lt $totalPlan) { 'Under plan' } else { 'On plan' }
}
}
4. What Happened When It Ran
The actual captured output, errors, and exit status.
PowerShell version: 7.6.6
Command: pwsh -NoLogo -NoProfile -NonInteractive -File ./run.ps1
Exit status: 0
STDOUT:
Category Plan Actual Variance VariancePct Direction
-------- ---- ------ -------- ----------- ---------
Cloud 1200.00 1345.50 145.50 12.12 Over plan
Training 800.00 640.00 -160.00 -20.00 Under plan
Travel 500.00 500.00 0.00 0.00 On plan
TOTAL 2500.00 2485.50 -14.50 -0.58 Under plan
STDERR:
(empty)
5. Validation Performed by the AI Workflow
The runtime, expected results, and safety boundaries were checked and recorded.
three categories and a total were calculated with decimal arithmetic and stable ordering.
Safety
fictional in-memory records only; no network, file writes, deletion, registry/system changes, credential access, or arbitrary code execution.
Lab · 2026-09-17
Support Queue Aging Report
Classify fictional support items by age and priority as of a fixed reporting date.
Validated
PowerShell 7 implementation
1. The Prompt AI Created for This Idea
After finding the scenario, AI turned it into this concise prompt. That prompt was then used to generate the PowerShell.
Create a fully commented PowerShell 7 script that accepts fictional support items with an opened date and priority, calculates age as of a supplied date, and assigns an age bucket. Return structured rows and bucket counts using in-memory data only; no network, files, credentials, registry, system changes, or arbitrary code.
2. The Runner AI Created
AI also created run.ps1. It prepares the sample data, passes the parameters, and invokes the generated PowerShell.
# Supply fictional tickets and a fixed reporting date.
$sample = @(
[pscustomobject]@{ Id = 'SUP-104'; Priority = 'High'; Opened = '2026-09-16' }
[pscustomobject]@{ Id = 'SUP-105'; Priority = 'Low'; Opened = '2026-09-12' }
[pscustomobject]@{ Id = 'SUP-106'; Priority = 'Medium'; Opened = '2026-09-01' }
[pscustomobject]@{ Id = 'SUP-107'; Priority = 'High'; Opened = '2026-09-15' }
)
# Run the aging report without touching a real ticketing system.
$result = @(& "$PSScriptRoot/solution.ps1" -Ticket $sample -AsOfDate ([datetime]'2026-09-17'))
# Display ticket details and bucket counts as two readable tables.
$result | Where-Object Kind -eq 'Detail' |
Format-Table Id, Priority, Opened, DaysOpen, Bucket -AutoSize
$result | Where-Object Kind -eq 'BucketSummary' |
Format-Table Bucket, Count -AutoSize
3. The PowerShell AI Generated
solution.ps1 is the runnable PowerShell produced from the AI-created prompt.
[CmdletBinding()]
param(
# Accept support records from the pipeline or as an array.
[Parameter(Mandatory, ValueFromPipeline)]
[psobject[]]$Ticket,
# Use an explicit date so the report is deterministic.
[Parameter(Mandatory)]
[datetime]$AsOfDate
)
begin {
# Buffer records before calculating detail and summary output.
$tickets = [System.Collections.Generic.List[psobject]]::new()
}
process {
# Store each incoming ticket in memory.
foreach ($item in $Ticket) {
$tickets.Add($item)
}
}
end {
# Calculate age and a readable bucket for every ticket.
$rows = foreach ($item in $tickets) {
# Parse the supplied ISO date without contacting any external system.
$opened = [datetime]::ParseExact([string]$item.Opened, 'yyyy-MM-dd', $null)
$daysOpen = [math]::Max(0, ($AsOfDate.Date - $opened.Date).Days)
# Use short, mutually exclusive age ranges.
$bucket = if ($daysOpen -le 2) { '0-2 days' } elseif ($daysOpen -le 7) { '3-7 days' } else { '8+ days' }
# Return a structured row for downstream formatting or export.
[pscustomobject]@{
Kind = 'Detail'
Id = [string]$item.Id
Priority = [string]$item.Priority
Opened = $opened.ToString('yyyy-MM-dd')
DaysOpen = $daysOpen
Bucket = $bucket
}
}
# Emit details in oldest-first order, then a compact bucket summary.
$rows | Sort-Object -Property DaysOpen, Priority, Id -Descending
$rows | Group-Object Bucket | Sort-Object Name | ForEach-Object {
[pscustomobject]@{
Kind = 'BucketSummary'
Bucket = $_.Name
Count = $_.Count
}
}
}
4. What Happened When It Ran
The actual captured output, errors, and exit status.
PowerShell version: 7.6.6
Command: pwsh -NoLogo -NoProfile -NonInteractive -File ./run.ps1
Exit status: 0
STDOUT:
Id Priority Opened DaysOpen Bucket
-- -------- ------ -------- ------
SUP-106 Medium 2026-09-01 16 8+ days
SUP-105 Low 2026-09-12 5 3-7 days
SUP-107 High 2026-09-15 2 0-2 days
SUP-104 High 2026-09-16 1 0-2 days
Bucket Count
------ -----
0-2 days 2
3-7 days 1
8+ days 1
STDERR:
(empty)
5. Validation Performed by the AI Workflow
The runtime, expected results, and safety boundaries were checked and recorded.
four tickets were parsed, assigned to deterministic age buckets, and ordered by age.
Safety
fictional in-memory records only; no network, file writes, deletion, registry/system changes, credential access, or arbitrary code execution.
Lab · 2026-09-17
Expense Workbook Summary
Round-trip fictional expenses through Excel and summarize totals by category.
Validated
PowerShell 7 implementation
1. The Prompt AI Created for This Idea
After finding the scenario, AI turned it into this concise prompt. That prompt was then used to generate the PowerShell.
Create a fully commented PowerShell 7 script that exports fictional expense rows to a formatted Excel table, imports the workbook, and returns category totals and a grand total. Use ImportExcel and a caller-supplied temporary path; use deterministic sample data and no network, credentials, registry/system changes, deletion, or arbitrary code.
2. The Runner AI Created
AI also created run.ps1. It prepares the sample data, passes the parameters, and invokes the generated PowerShell.
# Use a temporary workbook path so the example does not touch a project file.
$workbook = Join-Path ([System.IO.Path]::GetTempPath()) 'idea-lab-expense-summary.xlsx'
# Provide fictional expenses across a few categories.
$sample = @(
[pscustomobject]@{ Date = '2026-09-01'; Category = 'Travel'; Amount = 425.00; Note = 'Rail' }
[pscustomobject]@{ Date = '2026-09-03'; Category = 'Training'; Amount = 180.00; Note = 'Workshop' }
[pscustomobject]@{ Date = '2026-09-08'; Category = 'Travel'; Amount = 95.50; Note = 'Taxi' }
[pscustomobject]@{ Date = '2026-09-10'; Category = 'Supplies'; Amount = 72.25; Note = 'Adapters' }
)
# Run the workbook round trip and display the returned summaries.
& "$PSScriptRoot/solution.ps1" -Expense $sample -OutputPath $workbook |
Format-Table Category, Rows, Total, WorkbookPath, Verified -AutoSize
3. The PowerShell AI Generated
solution.ps1 is the runnable PowerShell produced from the AI-created prompt.
[CmdletBinding()]
param(
# Accept expense rows from the pipeline or as an array.
[Parameter(Mandatory, ValueFromPipeline)]
[psobject[]]$Expense,
# Write only to the path supplied by the caller.
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string]$OutputPath
)
begin {
# Buffer the input so one workbook and one summary are produced.
$expenses = [System.Collections.Generic.List[psobject]]::new()
}
process {
# Add each fictional row to the in-memory collection.
foreach ($item in $Expense) {
$expenses.Add($item)
}
}
end {
# Load the cross-platform workbook cmdlets supplied by ImportExcel.
Import-Module ImportExcel -ErrorAction Stop -WarningAction SilentlyContinue
# Suppress the optional graphics dependency warning in a headless runtime.
$WarningPreference = 'SilentlyContinue'
# Export a simple, filterable table with readable headers.
$expenses | Export-Excel -Path $OutputPath -WorksheetName 'Expenses' -TableName 'ExpenseTable' -AutoFilter -FreezeTopRow -BoldTopRow -WarningAction SilentlyContinue 3>$null
# Read the workbook back to prove that the round trip preserved the rows.
$roundTrip = @(Import-Excel -Path $OutputPath -WorksheetName 'Expenses')
# Group the imported rows and calculate deterministic totals.
$byCategory = $roundTrip | Group-Object Category | Sort-Object Name | ForEach-Object {
[pscustomobject]@{
Category = $_.Name
Rows = $_.Count
Total = [decimal](($_.Group | Measure-Object Amount -Sum).Sum)
}
}
# Emit category summaries followed by a verification row.
$byCategory
[pscustomobject]@{
Category = 'TOTAL'
Rows = $roundTrip.Count
Total = [decimal](($roundTrip | Measure-Object Amount -Sum).Sum)
WorkbookPath = $OutputPath
Verified = $roundTrip.Count -eq $expenses.Count
}
}
4. What Happened When It Ran
The actual captured output, errors, and exit status.
PowerShell version: 7.6.6
Command: pwsh -NoLogo -NoProfile -NonInteractive -File ./run.ps1
Exit status: 0
STDOUT:
WARNING: ImportExcel Module Cannot Autosize. Please run the following command to install dependencies:
apt-get -y update && apt-get install -y --no-install-recommends libgdiplus libc6-dev
Category Rows Total WorkbookPath Verified
-------- ---- ----- ------------- --------
Supplies 1 72.25
Training 1 180.00
Travel 2 520.50
TOTAL 4 772.75 <temporary-workbook> True
STDERR:
(empty)
5. Validation Performed by the AI Workflow
The runtime, expected results, and safety boundaries were checked and recorded.
empty. The headless runtime also printed ImportExcel's optional graphics dependency warning on standard output.
Checks
four rows round-tripped through a formatted workbook; category totals and grand total matched.
Safety
fictional records and a caller-supplied temporary workbook path; no network, deletion, registry/system changes, credential access, or arbitrary code execution.
Lab · 2026-09-17
Command Latency Percentiles
Turn fictional duration samples into stable median and 95th-percentile reports.
Validated
PowerShell 7 implementation
1. The Prompt AI Created for This Idea
After finding the scenario, AI turned it into this concise prompt. That prompt was then used to generate the PowerShell.
Create a fully commented PowerShell 7 script that accepts fictional command-duration records, calculates count, minimum, average, median, and 95th percentile per command, and returns stable structured output. Use only in-memory numbers; no files, network, credentials, registry/system changes, or arbitrary code.
2. The Runner AI Created
AI also created run.ps1. It prepares the sample data, passes the parameters, and invokes the generated PowerShell.
two commands were grouped, sorted, and summarized with deterministic nearest-rank percentiles.
Safety
fictional in-memory numbers only; no network, file writes, deletion, registry/system changes, credential access, or arbitrary code execution.
Lab · 2026-09-17
Token Budget Planner
Estimate fictional model usage and compare the total with a token budget.
Validated
PowerShell 7 implementation
1. The Prompt AI Created for This Idea
After finding the scenario, AI turned it into this concise prompt. That prompt was then used to generate the PowerShell.
Create a fully commented PowerShell 7 script that accepts fictional model usage records, estimates total tokens from request counts and average tokens, and marks the total within or over a supplied budget. Return structured rows and totals using in-memory data only; no network, files, credentials, registry, system changes, or arbitrary code.
2. The Runner AI Created
AI also created run.ps1. It prepares the sample data, passes the parameters, and invokes the generated PowerShell.
# Use fictional model usage records for a deterministic planning example.
$sample = @(
[pscustomobject]@{ Model = 'Model-A'; Requests = 120; AverageTokens = 320 }
[pscustomobject]@{ Model = 'Model-B'; Requests = 80; AverageTokens = 540 }
[pscustomobject]@{ Model = 'Model-C'; Requests = 40; AverageTokens = 250 }
)
# Estimate usage against a 100,000-token sample budget.
& "$PSScriptRoot/solution.ps1" -Model $sample -BudgetTokens 100000 |
Format-Table Model, Requests, EstimatedTokens, SharePct, BudgetStatus -AutoSize
3. The PowerShell AI Generated
solution.ps1 is the runnable PowerShell produced from the AI-created prompt.
[CmdletBinding()]
param(
# Accept model usage records from the pipeline or as an array.
[Parameter(Mandatory, ValueFromPipeline)]
[psobject[]]$Model,
# Set a simple fictional budget in token units for the sample.
[ValidateRange(1, 1000000000)]
[long]$BudgetTokens = 100000
)
begin {
# Buffer records so shares and totals use one consistent denominator.
$models = [System.Collections.Generic.List[psobject]]::new()
}
process {
# Add every fictional model row to memory.
foreach ($item in $Model) {
$models.Add($item)
}
}
end {
# Calculate estimated usage for each model.
$rows = foreach ($item in $models) {
# Multiply request volume by average tokens per request.
$estimated = [long]$item.Requests * [long]$item.AverageTokens
[pscustomobject]@{
Model = [string]$item.Model
Requests = [long]$item.Requests
AverageTokens = [long]$item.AverageTokens
EstimatedTokens = $estimated
}
}
# Compute a total before calculating each model's share.
$total = ($rows | Measure-Object EstimatedTokens -Sum).Sum
foreach ($row in ($rows | Sort-Object Model)) {
# Avoid division by zero for an empty workload.
$share = if ($total -eq 0) { 0 } else { [math]::Round(($row.EstimatedTokens / $total) * 100, 2) }
[pscustomobject]@{
Model = $row.Model
Requests = $row.Requests
EstimatedTokens = $row.EstimatedTokens
SharePct = $share
BudgetStatus = if ($total -le $BudgetTokens) { 'Within budget' } else { 'Over budget' }
}
}
# Emit one total row so the budget decision is visible at a glance.
[pscustomobject]@{
Model = 'TOTAL'
Requests = [long](($rows | Measure-Object Requests -Sum).Sum)
EstimatedTokens = [long]$total
SharePct = 100
BudgetStatus = if ($total -le $BudgetTokens) { 'Within budget' } else { 'Over budget' }
}
}
4. What Happened When It Ran
The actual captured output, errors, and exit status.
PowerShell version: 7.6.6
Command: pwsh -NoLogo -NoProfile -NonInteractive -File ./run.ps1
Exit status: 0
STDOUT:
Model Requests EstimatedTokens SharePct BudgetStatus
----- -------- --------------- -------- ------------
Model-A 120 38400 41.92 Within budget
Model-B 80 43200 47.16 Within budget
Model-C 40 10000 10.92 Within budget
TOTAL 240 91600 100 Within budget
STDERR:
(empty)
5. Validation Performed by the AI Workflow
The runtime, expected results, and safety boundaries were checked and recorded.
three model rows were estimated, shares were calculated, and the total stayed within the sample budget.
Safety
fictional in-memory numbers only; no network, file writes, deletion, registry/system changes, credential access, or arbitrary code execution.
Lab · 2026-09-16
Preview Feature Readiness
Compare a fictional feature catalog with the current PowerShell version and flag what is ready.
Validated
PowerShell 7 implementation
1. The Prompt AI Created for This Idea
After finding the scenario, AI turned it into this concise prompt. That prompt was then used to generate the PowerShell.
Create a fully commented PowerShell 7 script that accepts fictional feature records (name, introduced version, and status), compares them with a configurable current PowerShell version, and returns a structured readiness report with next steps. Use only in-memory data and version-aware validation; no network, file, credential, registry, or system access.
2. The Runner AI Created
AI also created run.ps1. It prepares the sample data, passes the parameters, and invokes the generated PowerShell.
# Keep the runner independent from the caller's machine and PowerShell installation.
$ErrorActionPreference = 'Stop'
# Supply a small fictional feature catalog with both available and future entries.
$features = @(
[pscustomobject]@{ Name = 'Structured error views'; IntroducedIn = '7.6'; Notes = 'Use the richer error display.' }
[pscustomobject]@{ Name = 'Preview pipeline insight'; IntroducedIn = '7.7'; Notes = 'Evaluate this preview feature first.' }
[pscustomobject]@{ Name = 'Cross-platform remoting'; IntroducedIn = '7.4'; Notes = 'Available in the current baseline.' }
)
# Run the solution against a fixed version so the output is repeatable.
& (Join-Path $PSScriptRoot 'solution.ps1') -Feature $features -CurrentVersion '7.6'
3. The PowerShell AI Generated
solution.ps1 is the runnable PowerShell produced from the AI-created prompt.
[CmdletBinding()]
param(
# Accept feature records from the caller so the report works with any in-memory catalog.
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[object[]] $Feature,
# Compare every feature with this explicit PowerShell version.
[version] $CurrentVersion = [version]'7.6'
)
# Make uninitialized variables and common scripting mistakes fail early.
Set-StrictMode -Version Latest
function Get-FeatureReadiness {
[CmdletBinding()]
param(
# Keep the input strongly typed and require at least one record.
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[object[]] $InputFeature,
# Pass the version into the function so the comparison is explicit and testable.
[Parameter(Mandatory)]
[version] $TargetVersion
)
foreach ($item in $InputFeature) {
# Validate the fields needed to produce a useful report row.
if ([string]::IsNullOrWhiteSpace([string]$item.Name)) {
throw 'Every feature must have a non-empty Name.'
}
if ($null -eq $item.IntroducedIn) {
throw "Feature '$($item.Name)' must specify IntroducedIn."
}
# Parse the version text once so malformed input fails with a clear message.
try {
$introducedVersion = [version]$item.IntroducedIn
}
catch {
throw "Feature '$($item.Name)' has an invalid IntroducedIn value: $($item.IntroducedIn)."
}
# Emit structured data rather than strings so the result remains reusable.
[pscustomobject]@{
Name = [string]$item.Name
IntroducedIn = $introducedVersion.ToString()
Available = $introducedVersion -le $TargetVersion
Recommendation = if ($introducedVersion -le $TargetVersion) {
'Ready to use'
}
else {
"Wait for PowerShell $introducedVersion"
}
Notes = [string]$item.Notes
}
}
}
# Build the report against the requested version.
$report = @(Get-FeatureReadiness -InputFeature $Feature -TargetVersion $CurrentVersion)
# Print a compact table that is easy to read in a terminal.
$report | Format-Table -AutoSize
# Print a summary so callers can see the overall readiness at a glance.
[pscustomobject]@{
CurrentVersion = $CurrentVersion.ToString()
FeatureCount = $report.Count
ReadyCount = @($report | Where-Object Available).Count
WaitingCount = @($report | Where-Object { -not $_.Available }).Count
} | Format-List
4. What Happened When It Ran
The actual captured output, errors, and exit status.
PowerShell version: 7.6.6
Command: pwsh -NoLogo -NoProfile -NonInteractive -File ./run.ps1
Exit status: 0
STDOUT:
Name IntroducedIn Available Recommendation Notes
---- ------------ --------- -------------- -----
Structured error views 7.6 True Ready to use Use th…
Preview pipeline insight 7.7 False Wait for PowerShell 7.7 Evalua…
Cross-platform remoting 7.4 True Ready to use Availa…
CurrentVersion : 7.6
FeatureCount : 3
ReadyCount : 2
WaitingCount : 1
STDERR:
(empty)
5. Validation Performed by the AI Workflow
The runtime, expected results, and safety boundaries were checked and recorded.
three in-memory feature records were compared with version 7.6; two were ready and one was correctly marked as waiting for a future version.
Safety
fictional data only; no network, file writes, deletion, registry/system changes, credential access, or arbitrary code execution.
Lab · 2026-09-16
Regional Sales Workbook
Round-trip fictional regional sales through an Excel workbook and verify the totals.
Validated
PowerShell 7 implementation
1. The Prompt AI Created for This Idea
After finding the scenario, AI turned it into this concise prompt. That prompt was then used to generate the PowerShell.
Create a fully commented PowerShell 7 script that exports fictional regional sales objects to a formatted Excel table, imports it, and verifies row count and total sales. Use ImportExcel and a caller-supplied temporary path, with deterministic sample data and no network, credentials, registry/system changes, deletion, or arbitrary code execution.
2. The Runner AI Created
AI also created run.ps1. It prepares the sample data, passes the parameters, and invokes the generated PowerShell.
# Stop on the first error so the captured exit status reflects the real result.
$ErrorActionPreference = 'Stop'
# Use the runtime temporary directory so the repository stays focused on source and evidence.
$outputPath = Join-Path ([System.IO.Path]::GetTempPath()) "idea-lab-regional-sales-$PID.xlsx"
# Supply deterministic fictional sales records.
$sales = @(
[pscustomobject]@{ Region = 'North'; Product = 'Atlas'; Units = 12; Amount = 1440.00 }
[pscustomobject]@{ Region = 'South'; Product = 'Beacon'; Units = 9; Amount = 990.00 }
[pscustomobject]@{ Region = 'West'; Product = 'Cedar'; Units = 15; Amount = 2025.00 }
[pscustomobject]@{ Region = 'North'; Product = 'Drift'; Units = 7; Amount = 840.00 }
)
# Invoke the ImportExcel-backed solution and print its verification object.
& (Join-Path $PSScriptRoot 'solution.ps1') -SalesRecord $sales -OutputPath $outputPath | Format-List
3. The PowerShell AI Generated
solution.ps1 is the runnable PowerShell produced from the AI-created prompt.
[CmdletBinding()]
param(
# Accept fictional sales rows from the caller.
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[object[]] $SalesRecord,
# Write the generated workbook only to the caller's chosen path.
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string] $OutputPath
)
# Make uninitialized variables and common scripting mistakes fail early.
Set-StrictMode -Version Latest
# Load the module that provides cross-platform Excel file operations.
Import-Module ImportExcel -ErrorAction Stop -WarningAction SilentlyContinue 3>$null
# Validate the output location without creating or changing any parent directory.
$parentPath = Split-Path -Parent $OutputPath
if (-not [string]::IsNullOrWhiteSpace($parentPath) -and -not (Test-Path -LiteralPath $parentPath -PathType Container)) {
throw "The output directory does not exist: $parentPath"
}
# Validate each record before writing a workbook so bad input is reported early.
foreach ($record in $SalesRecord) {
if ([string]::IsNullOrWhiteSpace([string]$record.Region)) {
throw 'Every sales record must have a Region.'
}
if ($null -eq $record.Amount) {
throw "Sales record '$($record.Region)' must have an Amount."
}
}
# Export the in-memory records with a table and presentation-friendly options.
$SalesRecord | Export-Excel -Path $OutputPath -WorksheetName 'Sales' -TableName 'RegionalSales' -AutoFilter -FreezeTopRow -BoldTopRow
# Read the workbook back to prove that the generated artifact can be consumed.
$roundTrip = @(Import-Excel -Path $OutputPath -WorksheetName 'Sales')
# Return structured verification details instead of requiring callers to parse text.
[pscustomobject]@{
WorkbookPath = $OutputPath
RowsWritten = $SalesRecord.Count
RowsRead = $roundTrip.Count
TotalAmount = [math]::Round((@($roundTrip | Measure-Object -Property Amount -Sum).Sum), 2)
Verified = $roundTrip.Count -eq $SalesRecord.Count
}
4. What Happened When It Ran
The actual captured output, errors, and exit status.
four fictional sales rows were exported to a workbook, imported again, and verified with matching row counts and a total amount of 5295.
Safety
only a temporary sample workbook was created; no network calls, deletion, registry/system changes, credential access, or arbitrary code execution.
Lab · 2026-09-16
Pipeline Throughput Scorecard
Compare direct-loop and pipeline processing while confirming both approaches produce the same answer.
Validated
PowerShell 7 implementation
1. The Prompt AI Created for This Idea
After finding the scenario, AI turned it into this concise prompt. That prompt was then used to generate the PowerShell.
Create a fully commented PowerShell 7 script that benchmarks a foreach loop and a pipeline over the same in-memory integers. Return elapsed milliseconds, checksums, and an agreement flag; keep the workload deterministic and note that timings vary. No files, network, credentials, registry/system changes, or arbitrary code.
2. The Runner AI Created
AI also created run.ps1. It prepares the sample data, passes the parameters, and invokes the generated PowerShell.
# Stop on the first error so the captured exit status is meaningful.
$ErrorActionPreference = 'Stop'
# Use a modest deterministic workload suitable for an isolated cloud runtime.
& (Join-Path $PSScriptRoot 'solution.ps1') -ItemCount 5000 -Repetitions 10
3. The PowerShell AI Generated
solution.ps1 is the runnable PowerShell produced from the AI-created prompt.
[CmdletBinding()]
param(
# Control the size of the fictional in-memory workload.
[ValidateRange(100, 100000)]
[int] $ItemCount = 5000,
# Repeat each implementation so a small workload still produces measurable timing.
[ValidateRange(1, 100)]
[int] $Repetitions = 10
)
# Make uninitialized variables and common scripting mistakes fail early.
Set-StrictMode -Version Latest
# Build one deterministic input array that both implementations will consume.
$items = 1..$ItemCount
# Measure a direct foreach loop over the same values.
$foreachMeasurement = Measure-Command {
$foreachSum = 0L
for ($repeat = 0; $repeat -lt $Repetitions; $repeat++) {
foreach ($item in $items) {
$foreachSum += $item
}
}
}
# Measure a pipeline-based implementation over the same values.
$pipelineMeasurement = Measure-Command {
$pipelineSum = 0L
for ($repeat = 0; $repeat -lt $Repetitions; $repeat++) {
$pipelineSum += ($items | ForEach-Object { $_ } | Measure-Object -Sum).Sum
}
}
# Emit structured results so the comparison can be consumed without parsing display text.
$scorecard = @(
[pscustomobject]@{
Implementation = 'foreach loop'
ElapsedMs = [math]::Round($foreachMeasurement.TotalMilliseconds, 3)
Checksum = $foreachSum
}
[pscustomobject]@{
Implementation = 'pipeline loop'
ElapsedMs = [math]::Round($pipelineMeasurement.TotalMilliseconds, 3)
Checksum = $pipelineSum
}
)
# Display the scorecard and an explicit agreement check.
$scorecard | Format-Table -AutoSize
[pscustomobject]@{
ItemCount = $ItemCount
Repetitions = $Repetitions
ChecksumsAgree = $scorecard[0].Checksum -eq $scorecard[1].Checksum
FasterPath = ($scorecard | Sort-Object ElapsedMs | Select-Object -First 1).Implementation
} | Format-List
4. What Happened When It Ran
The actual captured output, errors, and exit status.
direct-loop and pipeline-loop implementations processed the same 5,000-item workload for 10 repetitions, produced matching checksums, and returned a scorecard.
Safety
deterministic in-memory integers only; no network, file writes, deletion, registry/system changes, credential access, or arbitrary code execution.
Note
elapsed times are illustrative and vary by runtime.
Lab · 2026-09-16
Ordered Folder Depth Summary
Group fictional paths by top-level folder and depth while keeping the report stable and readable.
Validated
PowerShell 7 implementation
1. The Prompt AI Created for This Idea
After finding the scenario, AI turned it into this concise prompt. That prompt was then used to generate the PowerShell.
Create a fully commented PowerShell 7 script that accepts fictional forward-slash paths, normalizes them, and groups them by top-level folder and depth. Ignore blanks, preserve deterministic group order, and include counts plus each group’s deepest sample. Use in-memory strings only; do not inspect the real filesystem or access network, credentials, registry, or system settings.
2. The Runner AI Created
AI also created run.ps1. It prepares the sample data, passes the parameters, and invokes the generated PowerShell.
# Stop on the first error so the captured exit status reflects the real result.
$ErrorActionPreference = 'Stop'
# Supply fictional paths only; no real directories are inspected.
$paths = @(
'reports/2026/january/sales.csv'
'reports/2026/february/sales.csv'
'reports/2026/february/archive/notes.txt'
'exports/daily/status.json'
'exports/monthly/status.json'
' '
'reports//2026//march//sales.csv'
)
# Run the in-memory path summarizer.
& (Join-Path $PSScriptRoot 'solution.ps1') -Path $paths
3. The PowerShell AI Generated
solution.ps1 is the runnable PowerShell produced from the AI-created prompt.
[CmdletBinding()]
param(
# Accept sample paths from the caller rather than reading the local filesystem.
[Parameter(Mandatory)]
[ValidateNotNull()]
[string[]] $Path
)
# Make uninitialized variables and common scripting mistakes fail early.
Set-StrictMode -Version Latest
# Hold normalized path records in memory for grouping.
$records = foreach ($value in $Path) {
if ([string]::IsNullOrWhiteSpace($value)) {
continue
}
# Normalize separators and trim the edges before splitting into segments.
$normalized = ($value -replace '/+', '/').Trim('/')
if ([string]::IsNullOrWhiteSpace($normalized)) {
continue
}
# Count non-empty segments to calculate path depth.
$segments = @($normalized -split '/' | Where-Object { $_ })
[pscustomobject]@{
Path = $normalized
TopLevel = $segments[0]
Depth = $segments.Count
}
}
# Group records and sort the groups for repeatable output.
$summary = foreach ($group in ($records | Group-Object TopLevel | Sort-Object Name)) {
# Sort paths by depth and then name so the deepest sample is deterministic.
$deepest = $group.Group | Sort-Object Depth, Path | Select-Object -Last 1
[pscustomobject]@{
TopLevel = $group.Name
PathCount = $group.Count
MaximumDepth = ($group.Group | Measure-Object -Property Depth -Maximum).Maximum
DeepestExample = $deepest.Path
}
}
# Print structured summary rows followed by an overall count.
$summary | Format-Table -AutoSize
[pscustomobject]@{
InputCount = @($Path).Count
NormalizedCount = @($records).Count
GroupCount = @($summary).Count
} | Format-List
4. What Happened When It Ran
The actual captured output, errors, and exit status.
seven input strings produced six normalized paths in two deterministic top-level groups; repeated separators and blank input were handled as specified.
Safety
paths were sample strings only; the real filesystem was never enumerated, and there was no network, deletion, registry/system change, credential access, or arbitrary code execution.
Lab · 2026-09-16
Cross-Platform Delimiter Parser
Turn mixed-delimiter text into clean, ordered tokens with an explicit character array.
Validated
PowerShell 7 implementation
1. The Prompt AI Created for This Idea
After finding the scenario, AI turned it into this concise prompt. That prompt was then used to generate the PowerShell.
Create a fully commented PowerShell 7 script that parses caller-supplied delimited strings using an explicit configurable character array. Trim tokens, remove empty values, preserve order, and return the original text plus token count. Use in-memory samples only; no files, network, credentials, registry/system changes, deletion, or arbitrary code.
2. The Runner AI Created
AI also created run.ps1. It prepares the sample data, passes the parameters, and invokes the generated PowerShell.
# Stop on the first error so the captured exit status reflects the real result.
$ErrorActionPreference = 'Stop'
# Supply deterministic examples using different delimiter characters.
$values = @(
'alpha, beta,, gamma'
'north | south | east'
)
# Run each example with its matching explicit delimiter character array.
& (Join-Path $PSScriptRoot 'solution.ps1') -Value $values[0] -Delimiter ([char[]]',') | Format-List
& (Join-Path $PSScriptRoot 'solution.ps1') -Value $values[1] -Delimiter ([char[]]'|') | Format-List
3. The PowerShell AI Generated
solution.ps1 is the runnable PowerShell produced from the AI-created prompt.
[CmdletBinding()]
param(
# Accept one or more delimited values from the caller.
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string[]] $Value,
# Make the delimiter characters explicit for predictable PowerShell 7 behavior.
[char[]] $Delimiter = [char[]]','
)
# Make uninitialized variables and common scripting mistakes fail early.
Set-StrictMode -Version Latest
foreach ($text in $Value) {
if ([string]::IsNullOrWhiteSpace($text)) {
throw 'Value entries cannot be blank.'
}
# Split using the explicit character array and remove empty tokens.
$tokens = @(
$text.Split($Delimiter, [System.StringSplitOptions]::RemoveEmptyEntries) |
ForEach-Object { $_.Trim() } |
Where-Object { -not [string]::IsNullOrWhiteSpace($_) }
)
# Return a structured object so callers can use the tokens directly.
[pscustomobject]@{
Original = $text
TokenCount = $tokens.Count
Tokens = $tokens -join ' | '
}
}
4. What Happened When It Ran
The actual captured output, errors, and exit status.
PowerShell version: 7.6.6
Command: pwsh -NoLogo -NoProfile -NonInteractive -File ./run.ps1
Exit status: 0
STDOUT:
Original : alpha, beta,, gamma
TokenCount : 3
Tokens : alpha | beta | gamma
Original : north | south | east
TokenCount : 3
Tokens : north | south | east
STDERR:
(empty)
5. Validation Performed by the AI Workflow
The runtime, expected results, and safety boundaries were checked and recorded.
comma-delimited and pipe-delimited samples each produced three ordered, trimmed tokens with empty values removed.
Safety
caller-supplied strings only; no network, file writes, deletion, registry/system changes, credential access, or arbitrary code execution.
Lab · 2026-09-15
Inventory Gap Report
Compare a fictional device inventory with a readiness baseline and report exactly what needs attention.
Validated
PowerShell 7 implementation
1. The Prompt AI Created for This Idea
After finding the scenario, AI turned it into this concise prompt. That prompt was then used to generate the PowerShell.
# Prompt
Create a PowerShell 7 script that accepts device inventory objects with a name, operating system, memory in GB, and free disk space in GB. Compare each record with a configurable readiness baseline, report whether it is ready, and list every gap in plain language. Use fictional in-memory records, keep the evaluation read-only, and avoid network calls or system changes.
2. The Runner AI Created
AI also created run.ps1. It prepares the sample data, passes the parameters, and invokes the generated PowerShell.
# Stop on unexpected errors so validation records a meaningful exit status.
$ErrorActionPreference = 'Stop'
# Use fictional inventory records so the report is safe to run anywhere.
$inventory = @(
[pscustomobject]@{ Device = 'Northstar-01'; OperatingSystem = 'Windows 11'; MemoryGB = 32; FreeDiskGB = 120 }
[pscustomobject]@{ Device = 'Northstar-02'; OperatingSystem = 'Windows 10'; MemoryGB = 16; FreeDiskGB = 80 }
[pscustomobject]@{ Device = 'Northstar-03'; OperatingSystem = 'Windows 11'; MemoryGB = 8; FreeDiskGB = 35 }
)
# Evaluate the sample inventory against the default baseline.
$results = & "$PSScriptRoot/solution.ps1" -Device $inventory
# Print a readable one-line summary per device.
$results | ForEach-Object {
Write-Output ("{0}: {1}; gaps: {2}" -f $_.Device, $(if ($_.Ready) { 'Ready' } else { 'Review' }), $_.Gaps)
}
3. The PowerShell AI Generated
solution.ps1 is the runnable PowerShell produced from the AI-created prompt.
[CmdletBinding()]
param(
# Accept fictional inventory records from the pipeline or as an array.
[Parameter(Mandatory, ValueFromPipeline)]
[psobject[]]$Device,
# Define the minimum baseline that a device should satisfy.
[string]$RequiredOs = 'Windows 11',
[ValidateRange(1, 1024)]
[int]$MinimumMemoryGB = 16,
[ValidateRange(1, 4096)]
[int]$MinimumFreeDiskGB = 50
)
begin {
# Hold input records until the pipeline completes so the function can emit one report.
$devicesToReview = [System.Collections.Generic.List[psobject]]::new()
}
process {
# Add each incoming device to the in-memory inventory.
foreach ($item in $Device) {
$devicesToReview.Add($item)
}
}
end {
# Evaluate each device against the same explicit baseline.
foreach ($item in $devicesToReview) {
# Start an empty list of human-readable gaps for this device.
$gaps = [System.Collections.Generic.List[string]]::new()
# Record an operating-system gap when the device is outside the baseline.
if ($item.OperatingSystem -ne $RequiredOs) {
$gaps.Add("OS is $($item.OperatingSystem); required $RequiredOs")
}
# Record a memory gap when the installed amount is too small.
if ([int]$item.MemoryGB -lt $MinimumMemoryGB) {
$gaps.Add("Memory is $($item.MemoryGB) GB; required $MinimumMemoryGB GB")
}
# Record a storage gap when the free space is below the baseline.
if ([int]$item.FreeDiskGB -lt $MinimumFreeDiskGB) {
$gaps.Add("Free disk is $($item.FreeDiskGB) GB; required $MinimumFreeDiskGB GB")
}
# Emit one concise report object for the device.
[pscustomobject]@{
Device = $item.Device
Ready = $gaps.Count -eq 0
Gaps = if ($gaps.Count -eq 0) { 'None' } else { $gaps -join '; ' }
}
}
}
4. What Happened When It Ran
The actual captured output, errors, and exit status.
PowerShell: 7.6.6
Command: /opt/powershell/pwsh -NoLogo -NoProfile -NonInteractive -File run.ps1
Exit status: 0
STDOUT:
Northstar-01: Ready; gaps: None
Northstar-02: Review; gaps: OS is Windows 10; required Windows 11
Northstar-03: Review; gaps: Memory is 8 GB; required 16 GB; Free disk is 35 GB; required 50 GB
STDERR:
(empty)
5. Validation Performed by the AI Workflow
The runtime, expected results, and safety boundaries were checked and recorded.
Validation StatusPassed
Runtime
PowerShell 7.6.6 on Linux
Command
./run.ps1 - Safety review: fictional in-memory inventory only; no network, deletion, registry/system changes, credential access, or arbitrary code execution.
Checks
three devices were evaluated against the OS, memory, and free-disk baseline; the command exited with status 0 and reported actionable gaps.
Lab · 2026-09-15
Parallel Health Check Results
Run independent checks concurrently, then sort the results so every report stays stable and readable.
Validated
PowerShell 7 implementation
1. The Prompt AI Created for This Idea
After finding the scenario, AI turned it into this concise prompt. That prompt was then used to generate the PowerShell.
# Prompt
Create a PowerShell 7 script that accepts independent check records with a name, expected value, and observed value. Evaluate the checks concurrently with `ForEach-Object -Parallel`, using a bounded throttle limit. Make the worker logic self-contained, return `Pass` or `Review` for each check, and sort the final objects by check name so output is deterministic. Use only in-memory fictional data and do not contact real services.
2. The Runner AI Created
AI also created run.ps1. It prepares the sample data, passes the parameters, and invokes the generated PowerShell.
# Treat any unexpected PowerShell error as a failed validation.
$ErrorActionPreference = 'Stop'
# Define independent, fictional checks that can safely run in parallel.
$checks = @(
[pscustomobject]@{ Check = 'Config schema'; Expected = 'v3'; Observed = 'v3' }
[pscustomobject]@{ Check = 'Cache freshness'; Expected = 'Fresh'; Observed = 'Stale' }
[pscustomobject]@{ Check = 'Worker capacity'; Expected = 'Available'; Observed = 'Available' }
[pscustomobject]@{ Check = 'Feature flags'; Expected = 'Loaded'; Observed = 'Loaded' }
)
# Invoke the solution with a small throttle limit suitable for a demo machine.
$results = & "$PSScriptRoot/solution.ps1" -Check $checks -ThrottleLimit 3
# Print one stable line per result for easy review and validation.
$results | ForEach-Object {
Write-Output ("{0}: {1} (expected {2}, observed {3})" -f $_.Check, $_.State, $_.Expected, $_.Observed)
}
3. The PowerShell AI Generated
solution.ps1 is the runnable PowerShell produced from the AI-created prompt.
[CmdletBinding()]
param(
# Accept independent check definitions from the pipeline or as an array.
[Parameter(Mandatory, ValueFromPipeline)]
[psobject[]]$Check,
# Limit concurrent workers so the pattern remains predictable on small machines.
[ValidateRange(1, 32)]
[int]$ThrottleLimit = 3
)
begin {
# Collect all checks before starting workers so the input boundary is explicit.
$checksToRun = [System.Collections.Generic.List[psobject]]::new()
}
process {
# Add each check record to the in-memory work list.
foreach ($item in $Check) {
$checksToRun.Add($item)
}
}
end {
# Run each independent check in its own parallel runspace.
$results = $checksToRun | ForEach-Object -Parallel {
# Keep worker logic self-contained because a parallel runspace does not inherit local functions.
$isMatch = $_.Observed -eq $_.Expected
# Return a plain object that is easy to sort, display, or export.
[pscustomobject]@{
Check = $_.Check
Expected = $_.Expected
Observed = $_.Observed
State = if ($isMatch) { 'Pass' } else { 'Review' }
}
} -ThrottleLimit $ThrottleLimit
# Sort after the workers finish so output order is stable across runs.
$results | Sort-Object Check
}
4. What Happened When It Ran
The actual captured output, errors, and exit status.
The runtime, expected results, and safety boundaries were checked and recorded.
Validation StatusPassed
Runtime
PowerShell 7.6.6 on Linux
Command
./run.ps1 - Safety review: fictional in-memory records only; no network, deletion, registry/system changes, credential access, or arbitrary code execution.
Checks
four records were processed with a throttle limit of 3, output was sorted by check name, and the command exited with status 0.
Lab · 2026-09-15
Portable UTF-8 Export
Create a BOM-free UTF-8 CSV in memory and prove that non-ASCII text survives the round trip.
Validated
PowerShell 7 implementation
1. The Prompt AI Created for This Idea
After finding the scenario, AI turned it into this concise prompt. That prompt was then used to generate the PowerShell.
# Prompt
Create a PowerShell 7 script that accepts objects from the pipeline and produces a portable CSV document in memory. Use an explicit UTF-8 encoder without a byte-order mark, preserve non-ASCII characters, and return metadata showing the encoding, byte count, line count, and whether a BOM was present. Decode the generated bytes again and return the round-tripped CSV text so the runner can demonstrate the result. Use no network calls, credentials, system changes, or external input.
2. The Runner AI Created
AI also created run.ps1. It prepares the sample data, passes the parameters, and invokes the generated PowerShell.
# Stop immediately if the solution reports a terminating error.
$ErrorActionPreference = 'Stop'
# Build fictional records in memory so this demonstration needs no network or external files.
$records = @(
[pscustomobject]@{ Device = 'Atlas-01'; Owner = 'Zoë'; State = 'Ready' }
[pscustomobject]@{ Device = 'Borealis-02'; Owner = 'Miyuki'; State = 'Review' }
[pscustomobject]@{ Device = 'Cedar-03'; Owner = 'José'; State = 'Ready' }
)
# Invoke the reusable solution with the sample records.
$result = & "$PSScriptRoot/solution.ps1" -InputObject $records
# Print deterministic metadata followed by the portable CSV payload.
Write-Output "Encoding: $($result.Encoding)"
Write-Output "Byte count: $($result.ByteCount)"
Write-Output "Line count: $($result.LineCount)"
Write-Output "Has BOM: $($result.HasBom)"
Write-Output 'CSV payload:'
Write-Output $result.CsvText
3. The PowerShell AI Generated
solution.ps1 is the runnable PowerShell produced from the AI-created prompt.
[CmdletBinding()]
param(
# Accept the objects that should become rows in the export.
[Parameter(Mandatory, ValueFromPipeline)]
[psobject[]]$InputObject,
# Allow callers to choose another delimiter while keeping comma as the default.
[char]$Delimiter = ','
)
begin {
# Collect pipeline input so one complete CSV document can be produced at the end.
$rows = [System.Collections.Generic.List[psobject]]::new()
}
process {
# Add each incoming object to the in-memory collection.
foreach ($item in $InputObject) {
$rows.Add($item)
}
}
end {
# Convert the objects to normal CSV lines without the PowerShell type header.
$csvLines = @($rows | ConvertTo-Csv -NoTypeInformation -Delimiter $Delimiter)
# Use an explicit UTF-8 encoder that does not add a byte-order mark.
$utf8NoBom = [System.Text.UTF8Encoding]::new($false)
# Join the lines with the platform newline and encode the complete document.
$csvText = $csvLines -join [Environment]::NewLine
$bytes = $utf8NoBom.GetBytes($csvText)
# Decode the bytes again to prove that the generated payload is self-consistent.
$roundTripText = $utf8NoBom.GetString($bytes)
# Return useful metadata plus the text that a caller could save or transmit.
[pscustomobject]@{
Encoding = 'UTF-8 without BOM'
ByteCount = $bytes.Length
LineCount = $csvLines.Count
HasBom = $bytes.Length -ge 3 -and $bytes[0] -eq 0xEF -and $bytes[1] -eq 0xBB -and $bytes[2] -eq 0xBF
CsvText = $roundTripText
}
}
4. What Happened When It Ran
The actual captured output, errors, and exit status.
The runtime, expected results, and safety boundaries were checked and recorded.
Validation StatusPassed
Runtime
PowerShell 7.6.6 on Linux
Command
./run.ps1 - Safety review: in-memory sample data only; no network, deletion, registry/system changes, credential access, or arbitrary code execution.
Checks
the script completed with exit status 0, emitted UTF-8 metadata, reported no BOM, preserved non-ASCII sample text, and produced a CSV payload.
Lab · 2026-09-15
Package Notes Into Message-Sized Blocks
Divide a long note into predictable character-limited blocks while preserving every character and its order.
Validated
PowerShell 7 implementation
1. The Prompt AI Created for This Idea
After finding the scenario, AI turned it into this concise prompt. That prompt was then used to generate the PowerShell.
Create a fully commented PowerShell 7 script that splits a long text value into sequential, fixed-size character blocks.
Accept the text and a positive maximum character count as parameters. Preserve every character and the original order, return one structured object per block with its one-based number, character count, and text, and handle a final block that is shorter than the limit. Prefer a clear indexed loop using .NET string operations over an opaque regular-expression trick.
Include CmdletBinding, strict mode, parameter validation, and a useful error for an empty text value or non-positive block size. Keep the example safe for isolated execution: use only caller-supplied or fictional in-memory text; do not write files, call the network, access credentials, change the registry or system settings, execute arbitrary code, or use `Invoke-Expression`.
Provide a separate `run.ps1` that supplies a fictional multi-sentence note and a small limit so several blocks are produced. Display a compact report that makes the block order and character limits easy to verify. Include exact PowerShell 7 commands and state that the limit counts .NET string characters.
2. The Runner AI Created
AI also created run.ps1. It prepares the sample data, passes the parameters, and invokes the generated PowerShell.
[CmdletBinding()]
param()
# Keep the runner independent from files, services, and user-specific configuration.
Set-StrictMode -Version Latest
# Fictional text keeps the example deterministic and safe to run anywhere.
$sampleText = 'The morning handoff is ready. Review the queued work, confirm the owner for each item, and record the next action before the afternoon check-in.'
$solutionPath = Join-Path -Path $PSScriptRoot -ChildPath 'solution.ps1'
# A small limit forces several blocks so the ordering and final-short-block behavior are visible.
& $solutionPath -Text $sampleText -MaxCharacters 48
3. The PowerShell AI Generated
solution.ps1 is the runnable PowerShell produced from the AI-created prompt.
[CmdletBinding()]
param(
# The complete text to divide into blocks.
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string] $Text,
# The largest number of .NET string characters allowed in one block.
[Parameter(Mandatory)]
[ValidateRange(1, 1000000)]
[int] $MaxCharacters
)
# Make uninitialized variables and common scripting mistakes fail early.
Set-StrictMode -Version Latest
function Split-TextIntoBlocks {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string] $InputText,
[Parameter(Mandatory)]
[ValidateRange(1, 1000000)]
[int] $BlockSize
)
$blocks = [System.Collections.Generic.List[object]]::new()
# Advance by one block at a time so no character is skipped or repeated.
for ($start = 0; $start -lt $InputText.Length; $start += $BlockSize) {
# The final block may be shorter than the requested maximum.
$remaining = $InputText.Length - $start
$length = [Math]::Min($BlockSize, $remaining)
$blockText = $InputText.Substring($start, $length)
# Store structured data instead of requiring callers to parse display text.
[void] $blocks.Add([pscustomobject]@{
BlockNumber = $blocks.Count + 1
CharacterCount = $length
Text = $blockText
})
}
[object[]] $blocks
}
$blocks = Split-TextIntoBlocks -InputText $Text -BlockSize $MaxCharacters
Write-Output 'Blocks:'
foreach ($block in $blocks) {
# Escape line breaks in the display only; the Text property itself remains unchanged.
$displayText = $block.Text.Replace("`r", '<CR>').Replace("`n", '<LF>')
# Angle brackets make leading or trailing spaces visible in captured output.
Write-Output ("{0}. ({1} chars) <{2}>" -f $block.BlockNumber, $block.CharacterCount, $displayText)
}
Write-Output ''
Write-Output 'Summary:'
[pscustomobject]@{
InputCharacters = $Text.Length
MaxCharacters = $MaxCharacters
BlockCount = $blocks.Count
LargestBlock = ($blocks | Measure-Object -Property CharacterCount -Maximum).Maximum
} | Format-List
4. What Happened When It Ran
The actual captured output, errors, and exit status.
PowerShell version: 7.6.6
Command: pwsh -NoProfile -NonInteractive -File ./run.ps1
=== STDOUT ===
Blocks:
1. (48 chars) <The morning handoff is ready. Review the queued >
2. (48 chars) <work, confirm the owner for each item, and recor>
3. (48 chars) <d the next action before the afternoon check-in.>
Summary:
InputCharacters : 144
MaxCharacters : 48
BlockCount : 3
LargestBlock : 48
=== STDERR ===
(empty)
=== EXIT STATUS ===
0
5. Validation Performed by the AI Workflow
The runtime, expected results, and safety boundaries were checked and recorded.
Validation StatusPassed
PowerShell 7.6.6 was available in the isolated cloud Linux runtime. The runner completed non-interactively with exit status 0 and no stderr output. The captured output shows a 144-character in-memory note split into three ordered blocks of 48 characters each. The implementation uses string indexing and Substring, preserves all input characters, and keeps the largest block at the requested limit. The example is safe for isolated execution because it uses only fictional in-memory text and does not write files, use the network, access credentials, change the registry, execute arbitrary code, or modify system settings. Command used:
Lab · 2026-09-15
Validate Schedule Dates Without Stopping the Batch
Turn malformed dates into structured review results while the rest of the batch keeps moving.
Validated
PowerShell 7 implementation
1. The Prompt AI Created for This Idea
After finding the scenario, AI turned it into this concise prompt. That prompt was then used to generate the PowerShell.
Create a fully commented PowerShell 7 script that validates a batch of schedule records without stopping when one record contains an invalid date.
Accept objects with a Name and DueDate property. Parse each date using a normal PowerShell cmdlet with `-ErrorAction Stop` inside a per-record `try`/`catch`, so conversion failures become structured results while the loop continues. Return one result per input record with the name, normalized ISO date when valid, a Valid or Invalid status, and an error message when invalid. Include a final count of valid and invalid records.
Include CmdletBinding, strict mode, parameter validation, readable objects instead of string parsing, and deterministic sample data. Keep the example safe for isolated execution: use only fictional in-memory records; do not write files, call the network, access credentials, change the registry or system settings, execute arbitrary code, or use `Invoke-Expression`.
Provide a separate `run.ps1` that supplies two valid dates and one malformed date, then invokes the implementation non-interactively. Display the per-record results and summary. Include exact PowerShell 7 commands and explain why `-ErrorAction Stop` is needed for `try`/`catch` to handle non-terminating conversion errors.
2. The Runner AI Created
AI also created run.ps1. It prepares the sample data, passes the parameters, and invokes the generated PowerShell.
[CmdletBinding()]
param()
# Keep the runner independent from files, services, and user-specific configuration.
Set-StrictMode -Version Latest
# Fictional records deliberately include one malformed date to exercise per-item recovery.
$sampleSchedules = @(
[pscustomobject]@{
Name = 'Morning handoff'
DueDate = '2026-09-18'
}
[pscustomobject]@{
Name = 'Afternoon review'
DueDate = 'not-a-date'
}
[pscustomobject]@{
Name = 'Weekend summary'
DueDate = '2026-09-20'
}
)
$solutionPath = Join-Path -Path $PSScriptRoot -ChildPath 'solution.ps1'
# Every record is handled in memory; the malformed value should not stop later records.
& $solutionPath -Schedules $sampleSchedules
3. The PowerShell AI Generated
solution.ps1 is the runnable PowerShell produced from the AI-created prompt.
[CmdletBinding()]
param(
# Accept the schedule records from the caller so the validator can be reused.
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[object[]] $Schedules
)
# Make uninitialized variables and common scripting mistakes fail early.
Set-StrictMode -Version Latest
function Test-ScheduleDates {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[object[]] $InputSchedule
)
$results = [System.Collections.Generic.List[object]]::new()
foreach ($schedule in $InputSchedule) {
$name = [string] $schedule.Name
$rawDueDate = [string] $schedule.DueDate
if ([string]::IsNullOrWhiteSpace($name)) {
throw 'Every schedule record must have a non-empty Name.'
}
try {
# ErrorAction Stop promotes a conversion error so the catch block can capture it.
$parsedDate = Get-Date -Date $rawDueDate -ErrorAction Stop
[void] $results.Add([pscustomobject]@{
Name = $name
DueDate = $parsedDate.ToString('yyyy-MM-dd')
Status = 'Valid'
Error = $null
})
}
catch {
# Keep the failure attached to this record and continue with the next one.
[void] $results.Add([pscustomobject]@{
Name = $name
DueDate = $rawDueDate
Status = 'Invalid'
Error = $_.Exception.Message
})
}
}
[object[]] $results
}
$results = @(Test-ScheduleDates -InputSchedule $Schedules)
# Keep the main table compact and print error details separately so they are never truncated.
$table = $results |
Select-Object -Property Name, DueDate, Status |
Format-Table -AutoSize |
Out-String -Width 200
Write-Output $table.TrimEnd()
$invalidResults = @($results | Where-Object Status -eq 'Invalid')
if ($invalidResults.Count -gt 0) {
Write-Output ''
Write-Output 'Errors:'
foreach ($invalidResult in $invalidResults) {
Write-Output ("{0}: {1}" -f $invalidResult.Name, $invalidResult.Error)
}
}
Write-Output ''
Write-Output 'Summary:'
[pscustomobject]@{
TotalRecords = $results.Count
ValidRecords = @($results | Where-Object Status -eq 'Valid').Count
InvalidRecords = @($results | Where-Object Status -eq 'Invalid').Count
} | Format-List
4. What Happened When It Ran
The actual captured output, errors, and exit status.
PowerShell version: 7.6.6
Command: pwsh -NoProfile -NonInteractive -File ./run.ps1
=== STDOUT ===
Name DueDate Status
---- ------- ------
Morning handoff 2026-09-18 Valid
Afternoon review not-a-date Invalid
Weekend summary 2026-09-20 Valid
Errors:
Afternoon review: Cannot bind parameter 'Date'. Cannot convert value "not-a-date" to type "System.DateTime". Error: "The string 'not-a-date' was not recognized as a valid DateTime. There is an unknown word starting at index '0'."
Summary:
TotalRecords : 3
ValidRecords : 2
InvalidRecords : 1
=== STDERR ===
(empty)
=== EXIT STATUS ===
0
5. Validation Performed by the AI Workflow
The runtime, expected results, and safety boundaries were checked and recorded.
Validation StatusPassed
PowerShell 7.6.6 was available in the isolated cloud Linux runtime. The runner completed non-interactively with exit status 0 and no stderr output. The captured output shows three in-memory schedule records processed: two valid dates were normalized to ISO form, one malformed date was captured as Invalid, and the batch continued to the final record. The example is safe for isolated execution because it uses only fictional in-memory records and does not write files, use the network, access credentials, change the registry, execute arbitrary code, or modify system settings. Command used:
Lab · 2026-09-15
Deduplicate Labels Without Losing Order
Normalize messy labels while preserving the first spelling and the order in which values appeared.
Validated
PowerShell 7 implementation
1. The Prompt AI Created for This Idea
After finding the scenario, AI turned it into this concise prompt. That prompt was then used to generate the PowerShell.
Create a fully commented PowerShell 7 script that turns a messy list of text labels into a case-insensitive, first-seen-order list of unique labels.
Trim surrounding whitespace before comparing values. Preserve the spelling of the first occurrence, preserve the order in which unique labels first appear, and report the input count, unique count, and duplicate count. Use a typed .NET `HashSet[string]` configured with an ordinal case-insensitive comparer for membership checks, plus an ordered collection for the output. Return readable PowerShell objects or clearly formatted output rather than parsing strings.
Include CmdletBinding, strict mode, parameter validation, and useful errors for null or blank labels. Keep the example safe for isolated execution: use only caller-supplied or fictional in-memory data; do not write files, call the network, access credentials, change the registry or system settings, execute arbitrary code, or use `Invoke-Expression`.
Provide a separate `run.ps1` that supplies sample labels with different capitalization and whitespace, then invokes the implementation. Include exact PowerShell 7 commands and state the assumptions behind the normalization and first-seen behavior.
2. The Runner AI Created
AI also created run.ps1. It prepares the sample data, passes the parameters, and invokes the generated PowerShell.
[CmdletBinding()]
param()
# Keep the runner independent from files, services, and user-specific configuration.
Set-StrictMode -Version Latest
# Fictional labels exercise case differences, duplicate values, and surrounding whitespace.
$sampleLabels = @(
'PowerShell'
'powershell'
' Automation '
'Automation'
'Cloud'
'cloud'
'DevOps'
)
$solutionPath = Join-Path -Path $PSScriptRoot -ChildPath 'solution.ps1'
# The implementation only receives the in-memory sample array and performs no external actions.
& $solutionPath -Labels $sampleLabels
3. The PowerShell AI Generated
solution.ps1 is the runnable PowerShell produced from the AI-created prompt.
[CmdletBinding()]
param(
# Accept the labels from the caller so the function can be reused with any in-memory input.
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string[]] $Labels
)
# Make uninitialized variables and common scripting mistakes fail early.
Set-StrictMode -Version Latest
function Get-UniqueLabelReport {
[CmdletBinding()]
param(
# Require at least one label and keep the input strongly typed.
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string[]] $InputLabel
)
# HashSet provides fast membership checks. The comparer makes only the comparison
# case-insensitive; the first spelling is still retained in the ordered collection.
$seen = [System.Collections.Generic.HashSet[string]]::new(
[System.StringComparer]::OrdinalIgnoreCase
)
# List preserves the order in which each unique label is first encountered.
$orderedLabels = [System.Collections.Generic.List[string]]::new()
# Track repeated values separately so the report can explain what was removed.
$duplicateLabels = [System.Collections.Generic.List[string]]::new()
foreach ($label in $InputLabel) {
if ($null -eq $label) {
throw 'Labels cannot contain null values.'
}
# Normalization happens before both the membership test and the retained value.
$normalizedLabel = $label.Trim()
if ([string]::IsNullOrWhiteSpace($normalizedLabel)) {
throw 'Labels cannot be blank or whitespace-only.'
}
# Add returns true only when this normalized value was not already present.
if ($seen.Add($normalizedLabel)) {
[void] $orderedLabels.Add($normalizedLabel)
}
else {
[void] $duplicateLabels.Add($normalizedLabel)
}
}
# Return structured data so callers can consume the result without parsing display text.
[pscustomobject]@{
InputCount = $InputLabel.Count
UniqueCount = $orderedLabels.Count
DuplicateCount = $duplicateLabels.Count
UniqueLabels = [string[]] $orderedLabels
Duplicates = [string[]] $duplicateLabels
}
}
# Build the report from the caller's labels.
$report = Get-UniqueLabelReport -InputLabel $Labels
# Display the ordered unique values first so the main result is easy to scan.
Write-Output 'Unique labels (first-seen order):'
for ($index = 0; $index -lt $report.UniqueLabels.Count; $index++) {
Write-Output ("{0}. {1}" -f ($index + 1), $report.UniqueLabels[$index])
}
Write-Output ''
Write-Output 'Summary:'
[pscustomobject]@{
InputCount = $report.InputCount
UniqueCount = $report.UniqueCount
DuplicateCount = $report.DuplicateCount
Duplicates = if ($report.Duplicates.Count -gt 0) {
$report.Duplicates -join ', '
}
else {
'(none)'
}
} | Format-List
4. What Happened When It Ran
The actual captured output, errors, and exit status.
The runtime, expected results, and safety boundaries were checked and recorded.
Validation StatusPassed
PowerShell 7.6.6 was available in the isolated cloud Linux runtime. The runner completed non-interactively with exit status 0 and no stderr output. The captured output shows seven input labels reduced to four unique labels. Capitalization and surrounding whitespace were ignored for comparison, while the first spelling and first-seen order were retained. Three duplicate values were reported. The example is safe for isolated execution because it uses only fictional in-memory strings and does not write files, use the network, access credentials, change the registry, execute arbitrary code, or modify system settings. Command used:
Lab · 2026-09-15
Batch Status Change Preview
Preview a batch status change with ShouldProcess before anything is applied, even in an in-memory demo.
Validated
PowerShell 7 implementation
1. The Prompt AI Created for This Idea
After finding the scenario, AI turned it into this concise prompt. That prompt was then used to generate the PowerShell.
Create a fully commented PowerShell 7 script that previews a batch status change before applying it.
Use a small set of fictional in-memory work items with a name, current status, and target status. Implement the operation with the ShouldProcess pattern so it supports PowerShell's -WhatIf and -Confirm common parameters. In preview mode, report each change that would happen. In apply mode, update only the in-memory objects and return a clear result for every item.
Include CmdletBinding, strict mode, parameter validation, readable objects instead of string parsing, and a concise summary of planned versus applied changes. Keep the example safe for isolated execution: do not write files, call the network, change the registry, access credentials, modify system settings, or use Invoke-Expression.
Provide a separate run.ps1 that supplies sample data and invokes the implementation in preview mode. Include exact commands for previewing and applying the in-memory example, state assumptions, and explain why WhatIf should be the default for potentially destructive automation.
2. The Runner AI Created
AI also created run.ps1. It prepares the sample data, passes the parameters, and invokes the generated PowerShell.
[CmdletBinding()]
param()
# Keep the runner independent from external files and services.
Set-StrictMode -Version Latest
# Use fictional objects so the preview can be run safely anywhere.
$sampleItems = @(
[pscustomobject]@{
Name = 'Alpha'
CurrentStatus = 'Queued'
TargetStatus = 'Ready'
}
[pscustomobject]@{
Name = 'Bravo'
CurrentStatus = 'Ready'
TargetStatus = 'Ready'
}
[pscustomobject]@{
Name = 'Charlie'
CurrentStatus = 'Queued'
TargetStatus = 'Blocked'
}
)
$solutionPath = Join-Path -Path $PSScriptRoot -ChildPath 'solution.ps1'
# -WhatIf is intentional: it previews the plan and does not apply changes.
& $solutionPath -Items $sampleItems -WhatIf
3. The PowerShell AI Generated
solution.ps1 is the runnable PowerShell produced from the AI-created prompt.
[CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'Medium')]
param(
# Accept the work items from the caller so the example is easy to reuse.
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[object[]] $Items
)
# Make uninitialized variables and common scripting mistakes fail early.
Set-StrictMode -Version Latest
function Invoke-StatusPlan {
[CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'Medium')]
param(
# Each item must expose Name, CurrentStatus, and TargetStatus properties.
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[object[]] $InputObject
)
foreach ($item in $InputObject) {
# Read the properties once so the proposed action is easy to inspect.
$name = [string]$item.Name
$currentStatus = [string]$item.CurrentStatus
$targetStatus = [string]$item.TargetStatus
if ([string]::IsNullOrWhiteSpace($name)) {
throw 'Every item must have a non-empty Name.'
}
if ([string]::IsNullOrWhiteSpace($targetStatus)) {
throw "Item '$name' must have a non-empty TargetStatus."
}
if ($currentStatus -eq $targetStatus) {
[pscustomobject]@{
Name = $name
CurrentStatus = $currentStatus
TargetStatus = $targetStatus
Action = 'No change'
}
continue
}
# ShouldProcess honors -WhatIf and -Confirm for the caller.
$description = "Change status from '$currentStatus' to '$targetStatus'"
if ($PSCmdlet.ShouldProcess($name, $description)) {
# This example changes only the in-memory object supplied by the caller.
$item.CurrentStatus = $targetStatus
[pscustomobject]@{
Name = $name
CurrentStatus = $currentStatus
TargetStatus = $targetStatus
Action = 'Applied'
}
}
else {
# In WhatIf mode, describe the proposed change without applying it.
[pscustomobject]@{
Name = $name
CurrentStatus = $currentStatus
TargetStatus = $targetStatus
Action = 'Would change'
}
}
}
}
# Invoke-StatusPlan inherits the script-level -WhatIf and -Confirm settings.
$results = Invoke-StatusPlan -InputObject $Items
$results | Format-Table -AutoSize
[pscustomobject]@{
TotalItems = @($results).Count
Changes = @($results | Where-Object Action -in @('Applied', 'Would change')).Count
Applied = @($results | Where-Object Action -eq 'Applied').Count
PreviewOnly = @($results | Where-Object Action -eq 'Would change').Count
}
4. What Happened When It Ran
The actual captured output, errors, and exit status.
PowerShell version: 7.6.6
Command: pwsh -NoProfile -NonInteractive -File ./run.ps1
=== STDOUT ===
What if: Performing the operation "Change status from 'Queued' to 'Ready'" on target "Alpha".
What if: Performing the operation "Change status from 'Queued' to 'Blocked'" on target "Charlie".
Name CurrentStatus TargetStatus Action
---- ------------- ------------ ------
Alpha Queued Ready Would change
Bravo Ready Ready No change
Charlie Queued Blocked Would change
TotalItems Changes Applied PreviewOnly
---------- ------- ------- -----------
3 2 0 2
=== STDERR ===
(empty)
=== EXIT STATUS ===
0
5. Validation Performed by the AI Workflow
The runtime, expected results, and safety boundaries were checked and recorded.
Validation StatusPassed
PowerShell 7.6.6 was available in the isolated cloud Linux runtime. The runner completed non-interactively with exit status 0 and no stderr output. The captured output shows two proposed status changes, one item requiring no change, and zero applied changes. The -WhatIf path did not modify the fictional in-memory records. The example is safe for isolated execution because it uses only sample objects and does not write files, use the network, access credentials, change the registry, or modify system settings. Command used: