PowerShell TUI programs for Windows
I have already listed up different "native" TUI programs for Windows, and noted that it would be nice to have some TUI programs for interacting with the system settings.
In the last period, I had some time at my disposal, and experimented a little bit with PowerShell: I thought that I could put together something that I might use.
The first thing I wrote was something similar to cron.
I wanted to start a new task automatically, but did not want to learn how to use the task scheduler from the command line.
The idea behind cront is simple.
Add one new task to the task scheduler that evaluates a crontab file.
Thus, once the task is registered, I do not need to touch the task scheduler anymore, but simply edit a textual file with my favourite editor.
Later, I realized that I wanted to manage (in particular: to stop) some tasks that were set by other programs.
This is out of scope for a "port" of cron, keeping in sync a textual file, and whatever the task scheduler does is too error-prone.
So I decided to bite the bullet and try to write a TUI program to simplify my tasks.
It turns out that getting something usable, which means something for listing, enabling, and disabling tasks, was easier than expected. I spent most of the time making it more performant and adding some bells and whistles.
I am no expert in designing TUI interfaces; there are probably a lot of things I did wrong. The moment a "real" alternative comes up, I’ll probably ditch my scripts.
The most important primitive
Using clear and redrawing the screen is extremely slow.
What is orders of magnitude faster is redrawing only the pixels that changed.
For this task, I wrote one class and two helper functions:
class ScreenBuffer {
[Parameter(Mandatory)][char[][]]$Cells
[Parameter(Mandatory)][int]$Width
[Parameter(Mandatory)][int]$Height
ScreenBuffer([int]$width, [int]$height) {
$this.Width = $width;
$this.Height = $height;
$this.Cells = [char[][]]::new($height);
$blank = [string]::new(' ', $width).ToCharArray();
for ($y = 0; $y -lt $height; $y++) {
$this.Cells[$y] = $blank.Clone();
}
}
ScreenBuffer([ScreenBuffer]$other) {
$this.Width = $other.Width;
$this.Height = $other.Height;
$this.Cells = [char[][]]::new($this.Height);
for ($y = 0; $y -lt $this.Height; $y++) {
$this.Cells[$y] = [char[]]::new($this.Width);
[Array]::Copy($other.Cells[$y], $this.Cells[$y], $this.Width);
}
}
[void]SetLine([int]$y, [string]$text) {
if ($y -lt 0 -or $y -ge $this.Height) { return }
$line = $text.PadRight($this.Width)
$line.CopyTo(0, $this.Cells[$y], 0, $this.Width)
}
}
function Init-Buffers {
param(
[Parameter(Mandatory)][ref]$old,
[Parameter(Mandatory)][ref]$new
)
$width = [Math]::Max(1, $raw.WindowSize.Width);
$height = [Math]::Max(1, $raw.WindowSize.Height);
$old.Value = [ScreenBuffer]::new($width, $height);
$new.Value = [ScreenBuffer]::new($width, $height);
clear;
}
function Print-Diff {
param(
[Parameter(Mandatory)][ScreenBuffer]$Old,
[Parameter(Mandatory)][ScreenBuffer]$New
)
for ($y = 0; $y -lt $New.Height; $y++) {
$rowOld = $Old.Cells[$y];
$rowNew = $New.Cells[$y];
if([System.Linq.Enumerable]::SequenceEqual($rowOld, $rowNew)){ continue; }
$width = $New.Width;
$x = 0;
while ($x -lt $width) {
# Skip unchanged cells
if ($rowOld[$x] -ceq $rowNew[$x]) {
$x++;
continue;
}
# Found a changed region - find its end
$start = $x;
while ($x -lt $width -and $rowOld[$x] -cne $rowNew[$x]) {
$x++;
}
$length = $x - $start;
[Console]::SetCursorPosition($start, $y);
[Console]::Out.Write($rowNew, $start, $length);
[Array]::Copy($rowNew, $start, $rowOld, $start, $length);
}
}
}Unfortunately, class is not available on older PowerShell versions (Windows 7 in particular), so my script will not work unchanged on those systems.
ScreenBuffer is just a matrix as big as the terminal, and represents what is drawn.
The content can be set with setLine, which accepts a line number.
New-Buffers initialized two ScreenBuffer with the current screen size.
Print-Diff is where the magic happens.
It compares an "old" and a "new" ScreenBuffer, and scans for differences.
For every difference it finds, it prints the relevant content.
Then, it updates the old buffer with the new content.
Print-Diff had multiple bottlenecks: comparing, copying, and printing many values takes time, and the rendering was slow.
All issues were solved once I found out how to do some bulk operations:
[Array]::Copy($rowNew, $start, $rowOld, $start, $length)instead of copying elements one-by-one[string]::new($rowNew, $start, $length)to create new buffer[Console]::Writeinstead ofWrite-Host[Console]::Out.Writewith indeces instead of[Console]::Writeto avoid creating a new buffer
An error I had in this function, but found very late, was using -eq and -ne instead of -ceq and -cne.
The first two comparison operators are case insensitive!
So ScreenBuffer and Print-Diff are not particularly complicated, but they are the building blocks that the whole TUI relies on for rendering a fast and responsive UI.
Determine the UI
The function Draw-UI is responsible for filling a ScreenBuffer with the actual content.
The function interface makes it simpler to work than with ScreenBuffer directly.
In my case, I decided that the UI would consist of a header, a list of elements, and a status bar.
The function is not complex; the most complex part is calculating how many (and which) rows are to be stored in ScreenBuffer.
function Draw-UI {
param(
[Parameter(Mandatory)][ScreenBuffer]$buf,
[string[]]$Header,
$rows,
[Parameter(Mandatory)][int]$selected,
[Parameter(Mandatory)][int]$top,
[string]$status
)
for ($i = 0; $i -lt $Header.Count; $i++) {
$buf.SetLine($i, $Header[$i]);
}
$visibleHeight = $buf.Height - $Header.Count - 2;
if ($visibleHeight -lt 1) { return; }
$row = $Header.Count;
$maxName = ($rows.TaskName | Measure-Object -Maximum Length).Maximum;
if ($null -eq $maxName) { $maxName = 10; }
$maxName = [Math]::Max($maxName, 10);
$maxName = [Math]::Min($maxName, [Math]::Floor($buf.Width / 3));
$fmt = "{0,-2}{1,-$maxName} {2,-10} {3}";
$visibleRows = $rows | Select-Object -Skip $top -First $visibleHeight;
$index = $top;
foreach ($r in $visibleRows) {
$marker = if ($index -eq $selected) { '>' } else { ' ' };
$state = if ($r.Settings.Enabled) { "Enabled" } else { "Disabled" };
$line = $fmt -f $marker, $r.TaskName, $state, $r.TaskPath.Replace('\', '/');
$buf.SetLine($row, $line);
$row++;
$index++;
}
while ($row -lt ($buf.Height - 2)) {
$buf.SetLine($row, '');
$row++;
}
$buf.SetLine($buf.Height - 2, "-" * $buf.Width);
$buf.SetLine($buf.Height - 1, $status);
}The event loop
The event loop is essentially the rest of the script.
function Get-TaskRows {
return @(Get-ScheduledTask | Sort-Object TaskPath, TaskName);
}
function Invoke-CursesUI {
$raw = $Host.UI.RawUI
$old = $null;
$new = $null;
Write-Output "Loading scheduled tasks...";
$rows = Get-TaskRows;
$selected = 0;
$top = 0;
$status = "Loaded $($rows.Count) scheduled tasks";
Init-Buffers -old ([ref]$old) -new ([ref]$new);
try {
[Console]::CursorVisible = $false;
while ($true) {
$header = @(
"Task Scheduler TUI",
[string]("-" * [int]$new.Width)
);
$visibleHeight = [Math]::Max(1, $new.Height - $header.Count - 2)
$top = [Math]::Min($top, $selected);
$top = [Math]::Max($top, $selected - $visibleHeight + 1);
$top = [Math]::Max(0, $top);
Draw-UI -buf $new -Header $header -rows $rows -selected $selected -top $top -status $status;
Print-Diff -Old $old -New $new;
$status = "";
$key = $raw.ReadKey("NoEcho,IncludeKeyDown");
$mods = @()
if ($key.ControlKeyState -band 0x0003) { $mods += "Alt" }
if ($key.ControlKeyState -band 0x000C) { $mods += "Ctrl" }
if ($key.ControlKeyState -band 0x0010) { $mods += "Shift" }
if ($mods.Count -eq 0) { $mods = "None" }
$combo = "$($key.VirtualKeyCode):$mods"
switch ($combo) {
"38:None" { $selected = [Math]::Max(0, $selected - 1); } # UpArrow
"40:None" { $selected = [Math]::Min($selected + 1, [Math]::Max(0, $rows.Count - 1)); } # DownArrow
"81:None" { $_ = "48:Alt" } # Q = Quit
"121:None" { $_ = "48:Alt" } # F10 = Quit
"48:Alt" { return; } # Alt+0
}
}
} finally {
[Console]::CursorVisible = $true;
clear;
}
}With $key = $raw.ReadKey("NoEcho,IncludeKeyDown") the script is waiting for the user input; once a key is pressed, the corresponding action is executed; in this case, "selecting" a different task, or quitting the script.
In the next iteration of the while loop, the updated variables are passed to Draw-UI, and Print-Diff will update the screen accordingly.
Then the script waits again for the next input.
Since I do not know by heart the virtual key codes, I also added a default case that prints them out in the status bar for testing:
default {
$char = if ($key.Character) { $key.Character; } else { "<none>"; }
$status = "Unknown key: Char='$char' Code=$($key.VirtualKeyCode), Combo=$combo";
}At that point, one might be wondering if the effort was worth it.
After all, this TUI program is just a glorified call to Get-ScheduledTask | Sort-Object TaskPath, TaskName and pretty printed through to a pager.
A good pager would even offer more advanced functionalities than my first revision of the script.
Adding functionalities
Once I refined the building blocks and structures, adding new functionalities based on my needs was relatively simple.
For example, support for faster navigation with Home, PgUp, PgDn, End was trivial to add:
"33:None" { $selected = [Math]::Max(0, $selected - $visibleHeight); } # PgUp
"34:None" { $selected = [Math]::Min($selected + $visibleHeight, [Math]::Max(0, $rows.Count - 1)); } # PgDn
"36:None" { $selected = 0; } # Home
"35:None" { $selected = [Math]::Max(0, $rows.Count - 1); } # EndThe first real functionality worth its name was being able to enable and disable a task:
"32:None" { # Space - toggle between enabled/disabled
if ($rows.Count -eq 0) { continue; }
$item = $rows[$selected];
$status = if ( $item.Settings.Enabled ) { "Disabling $($item.TaskName)..." } else {"Enabling $($item.TaskName)..." };
Draw-UI -buf $new -Header $header -rows $rows -selected $selected -top $top -status $status;
Print-Diff -Old $old -New $new;
try {
if ( $item.Settings.Enabled ) {
Disable-ScheduledTask -TaskName $item.TaskName -TaskPath $item.TaskPath -ErrorAction Stop | Out-Null;
$status = "Disabled $($item.TaskName)";
} else {
Enable-ScheduledTask -TaskName $item.TaskName -TaskPath $item.TaskPath -ErrorAction Stop | Out-Null;
$status = "Enabled $($item.TaskName)";
}
$rows = Get-TaskRows;
} catch {
$status = "Failed to modify task '$($item.TaskName)': $_".Trim();
}
}Since Disable-ScheduledTask, Enable-ScheduledTask, and in particular Get-TaskRows (which calls Get-ScheduledTask) can take some time, I added an additional call to Draw-UI and Print-Diff to notify the user, with a message in the status bar, that something is happening.
Once I reached this point, I thought that writing this particular TUI script was worth the effort, as there was some real interaction with the system.
Adding other functionalities
On machines with a lot of tasks, being able to search or filter (preferably both) is an important feature. For this reason, I decided to add a filter functionality too.
Keep in mind that the presented solution is unnecessarily complicated for filtering the list, but I wanted to use the same solution also in other scripts.
If there had been a standard command-line editor, I would have tried to use it for asking the filter value from the user. But there is none on Windows, and I really wanted to just copy my script on a machine and be able to use it without any setup.
So I decided to implement a one-line editor/input dialog, which is probably not up to the name I just gave it, but seems to be good enough for my use cases.
function Show-ChooseDialog {
param(
[Parameter(Mandatory)][ScreenBuffer]$OldBuf,
[Parameter(Mandatory)][ScreenBuffer]$NewBuf,
[string]$Message = "Are you sure?",
[string[]]$Buttons = @("Yes", "No", "Cancel")
)
$btnLine = ""
foreach ($b in $Buttons) {
$btnLine += " $b ";
}
$width = [Math]::Max($btnLine.Length, $Message.Length) + 4;
$height = 7;
$left = [Math]::Floor(($NewBuf.Width - $width) / 2);
$top = [Math]::Floor(($NewBuf.Height - $height) / 2);
$sel = 0;
$NewBuf.SetLine($top+0, "/" + ("~" * ($width - 2)) + "\");
$NewBuf.SetLine($top+1, "|" + (" " * ($width - 2)) + "|");
$pad1 = [Math]::Floor(($width - $Message.Length) / 2) - 1;
$pad2 = [Math]::Ceiling(($width - $Message.Length) / 2) - 1;
$NewBuf.SetLine($top+2, "|" + (" " * $pad1) + $Message + (" " * $pad2) + "|" );
$NewBuf.SetLine($top+3, "|" + (" " * ($width - 2)) + "|");
$NewBuf.SetLine($top+5, "|" + (" " * ($width - 2)) + "|");
$NewBuf.SetLine($top+6, "\" + ("~" * ($width - 2)) + "/");
while ($true) {
$btnLine = "";
for ($i = 0; $i -lt $Buttons.Count; $i++) {
if ($i -eq $sel) {
$btnLine += "[ $($Buttons[$i]) ] ";
} else {
$btnLine += " $($Buttons[$i]) ";
}
}
# Center buttons
$pad = [Math]::Floor(($width - $btnLine.Length) / 2) - 1;
$NewBuf.SetLine($top + 4, "|" + (" " * $pad) + $btnLine + (" " * $pad) + "|");
Print-Diff -Old $OldBuf -New $NewBuf;
$key = [Console]::ReadKey($true);
switch ($key.Key) {
'LeftArrow' { $sel = ($sel - 1 + $Buttons.Count) % $Buttons.Count; }
'RightArrow' { $sel = ($sel + 1 ) % $Buttons.Count; }
'Enter' { return $Buttons[$sel]; }
'Escape' { return "Cancel"; }
'Q' { return "Cancel"; }
}
}
}
function Invoke-InlineEditor {
param(
[Parameter(Mandatory)][ScreenBuffer]$OldBuf,
[Parameter(Mandatory)][ScreenBuffer]$NewBuf,
[int]$Row = 0,
[Parameter(Mandatory)][string]$Description,
[string]$Prompt = "> ",
[string]$Confirmation = "",
[string]$Default = ""
)
$buffer = New-Object System.Collections.Generic.List[char];
$buffer.AddRange($Default.ToCharArray())
$cursor = $buffer.Count;
$line = $Prompt + (-join $buffer);
$NewBuf.SetLine($Row, ""); $Row++;
$NewBuf.SetLine($Row, "#" * $NewBuf.Width);$Row++;
$NewBuf.SetLine($Row, $Description);$Row++;
$NewBuf.SetLine($Row, $line);
$NewBuf.SetLine($Row+1, "#" * $NewBuf.Width);
$NewBuf.SetLine($Row+2, "");
try {
Print-Diff -Old $OldBuf -New $NewBuf;
[Console]::SetCursorPosition($Prompt.Length + $cursor, $Row);
[Console]::CursorVisible = $true;
while ($true) {
$key = [Console]::ReadKey($true);
if ( ($key.Modifiers -ceq "Alt" -and $key.KeyChar -ceq '0') -or ($key.Key -ceq 'Enter') -or ($key.Key -ceq 'F10') ) {
if( [string]::IsNullOrWhiteSpace($Confirmation)){
return -join $buffer;
} else {
$BeforeDialogBuf = [ScreenBuffer]::new($NewBuf);
[Console]::CursorVisible = $false;
$result = Show-ChooseDialog -OldBuf $OldBuf -NewBuf $NewBuf -Message $Confirmation;
if ("Yes" -ceq $result) { return -join $buffer; }
elseif ("No" -ceq $result) { return $null; }
elseif ("Cancel" -ceq $result) {
$NewBuf = $BeforeDialogBuf;
Print-Diff -Old $OldBuf -New $NewBuf;
[Console]::SetCursorPosition($Prompt.Length + $cursor, $Row);
[Console]::CursorVisible = $true;
continue;
}
}
}
switch ($key.Key) {
'LeftArrow' { $cursor = [Math]::Max(0, $cursor - 1); }
'RightArrow' { $cursor = [Math]::Min($buffer.Count, $cursor + 1); }
'Home' { $cursor = 0; }
'End' { $cursor = $buffer.Count; }
'Backspace' {
if ($cursor -gt 0) {
$cursor--;
$buffer.RemoveAt($cursor);
}
}
'Escape' { return $null; }
'Delete' {
if ($cursor -lt $buffer.Count) {
$buffer.RemoveAt($cursor);
}
}
default {
if ($key.KeyChar -le 32) { break; }
$buffer.Insert($cursor, $key.KeyChar);
$cursor++;
}
}
$line = $Prompt + (-join $buffer);
$NewBuf.SetLine($Row, $line);
Print-Diff -Old $OldBuf -New $NewBuf;
[Console]::SetCursorPosition($Prompt.Length + $cursor, $Row);
}
} finally {
[Console]::CursorVisible = $false;
}
}Invoke-InlineEditor works similarly to the event-loop; it renders the output through ScreenBuffer, listens for single key presses, and if configured appropriately, shows a confirmation dialog before exiting.
It is probably an over-engineered solution compared to using Read-Host, but Read-Host does not allow reacting to the user pressing Esc or other "special keys".
Another feature that was easy to implement, thanks to ScreenBuffer, is being able to store the current screen and restore it.
With $BeforeDialogBuf = [ScreenBuffer]::new($NewBuf); the buffer is stored in a separate variable, before showing the confirmation dialog.
If the user decides he wants to edit the text further (presses "Cancel"), then the Dialog is restored with $NewBuf = $BeforeDialogBuf; Print-Diff -Old $OldBuf -New $NewBuf;.
In my initial version, I used a switch instead of a chain of if-else, and I wondered for too long why it did not work as expected.
I learned the hard way that my continue inside a switch did not affect my while loop:
An unlabeled continue statement within a switch terminates execution of the current switch iteration and transfers control to the top of the switch to get the next input item.
A similar statement holds for break.
Also note that I am using [Console]::ReadKey($true) instead of $key = $raw.ReadKey("NoEcho,IncludeKeyDown").
I’m not exactly sure which of the two I should prefer, if one is superior to the other, except that the switch following [Console]::ReadKey($true) seems more legible.
As far as I’ve experienced, both seem to work equally well in the environment I tested, and those environments include:
PowerShell in Windows Terminal
cygwin bash in Windows Terminal
cmd in Windows Terminal
cmd.exepowershell.execygwin bash in mintty
PowerShell from
sshexecuted fromtmuxfrombashon a Linux machinePowerShell in the console integrated into the terminal in Visual Studio Code
So quit some environment, although there are many more virtual terminals for Windows, where maybe the difference between $raw.ReadKey and [Console]::ReadKey can play a significant role.
Once I finished implementing the inline editor, it was time to use it.
The first change was to introduce the variable $allrows, which contains, as the name implies, all rows (thus the output of Get-TaskRows), and store in $rows the filtered $rows.
I decided to bind both F and Ctrl+F for this task:
"70:Ctrl" { $_ = "70:None" } # CTRL+F
"70:None" { # F
$newFilter = Invoke-InlineEditor -OldBuf $old -NewBuf $new -Row ([Math]::Floor($new.Height / 3)) -Description "Write filter, leave empty to show all tasks, press Esc to cancel" -Prompt "Filter: " -Default $filter;
if( ($null -eq $newFilter) -or ($filter -eq $newFilter) ) { break; }
$filter = $newFilter;
$rows = @($allrows | Where-Object { $_.TaskName -match $filter });
$status="Filter '$filter' applied, showing $($rows.Count) scheduled tasks";
$selected = 0;
}And that was it.
Minor changes
Replace all -eq and -ne with -ceq and -cne when comparing strings by default.
Use [Console]::Error.WriteLine($message) instead of Write-Error $message to avoid powershell writing additional content.
Complete source
The complete source can be found on GitHub.
There are surely a lot of issues and anti-patterns, mostly dictated by my lack of knowledge of PowerShell. In particular, the fact that I copied and pasted the core routines between scripts.
I am sure there are better solutions, but nothing came to mind.
The end goal was to have one script I could copy and use immediately.
Without installing dependencies, changing $PATH, or something else.
If you have some suggestions, contributions are welcome!
A possible alternative would be to use a programming language that gets compiled to an .exe file; this would fix the setup and dependency issue, but it would require me to spend more time than I want to.
Conclusion
Building a TUI wrapper for Disable-ScheduledTask, Enable-ScheduledTask, and Get-ScheduledTask was just the beginning.
Once I had the appropriate primitives for showing and interacting with a sequence of elements, why not make similar programs for services.msc or the Windows firewall rules?
And last but not least, a registry editor?
All of these programs were relatively simple to write. It took me multiple iterations, but if I had realized previously how I could implement them, I would have done so.
I’m sure those programs do not handle multiple edge cases well; in particular, if they need to interact or display with something that is not ASCII.
But they are currently good enough for my needs, and I could not find anything else.
One further advantage of using a scripting language is that one can look at the source instead of trusting a binary blob or having to compile the executable before being able to use it.
It is always worth improving the working environment, it is the common denominator for most tasks.

If you have questions, comments, or found typos, the notes are not clear, or there are some errors; then just contact me.