Installing NVidia Graphics drivers on Ubuntu with Secure Boot

Running proprietary drivers, such as the NVIDIA Graphics Driver, on a Linux distribution with Secure Boot enabled is a procedure often complicated by specific toolchain failures. To replace a graphics card and install proprietary drivers, the system must sign the third-party modules to allow them to load. Your system may work fine with the default drivers that come with your distribution. However, on my system, my mouse left trails of white pixels on GitHub Desktop as I moved it around. After the fixes in this guide, the display is running perfectly. Also, the full capability of my GPU for Cuda tasks has been unlocked.

This comprehensive solution was developed and validated across multiple Ubuntu installations—from LTS versions to the latest release – proving its robustness against various kernel versions. We found that the standard signing process can fail due to a combination of three low-level bugs:

  1. The sign-file utility fails to handle password-protected private keys.
  2. The signing scripts do not account for ZSTD compression of kernel modules (.ko.zst).
  3. The mokutil import utility demands a DER key format, which is not the default output of standard key generation commands.

This guide documents the necessary workarounds to bypass these failures, resulting in a fully signed and functional NVIDIA driver running securely on any current Ubuntu system.

I have made use of Gemini and other AI for solving the issues described here and for the initial draft of this post.

Preamble: Diagnosis and Prerequisites

Before diving into the complex manual fix, you must confirm that Secure Boot is enabled and attempt the simplest installation method first.

Check Secure Boot Status

This command verifies if your operating system recognizes Secure Boot as being active:

mokutil --sb-state

If this shows disabled, you must enable it in your UEFI/BIOS before proceeding with this guide. Alternatively, if you currently don’t have Secure Boot and don’t want or need it then the standard installation may be sufficient. If you have Secure Boot enabled and the NVidia graphics drivers have not loaded, this guide may help.

The Quick Test: Standard Installation

On modern Ubuntu releases (like 25.10 “Questing”), the standard DKMS toolchain may already be patched, allowing a simple installation to succeed.

  1. Hit the Start key and search for “Additional Drivers”.
  2. Select the recommended NVIDIA driver for your system and click Apply Changes.
  3. Reboot the system.

Check NVIDIA Driver Status

Now we can check if the operating system has loaded the drivers.

# Check if the kernel modules are loaded
lsmod | grep nvidia

# Check if the NVIDIA card is recognized and functional
nvidia-smi

If the drivers have load successfully, you can stop here!

Expected Output (if the problem exists): The lsmod command may show no nvidia modules, or nvidia-smi may fail with an error like NVIDIA-SMI has failed because it couldn't communicate with the NVIDIA driver.

If both checks confirm Secure Boot is enabled and your NVIDIA drivers are failing, you are ready to begin the patching procedure.

Step 1: Key Generation and System Setup

Before tackling the bugs, we need a foundational element: a Machine Owner Key (MOK) pair. This pair consists of a private key (for signing modules) and a public certificate (for enrolling with UEFI/BIOS).

Prerequisites Check

Ensure you have the necessary tools and packages installed. The openssl utility and the kernel headers are essential for this process.

# Check if the openssl utility is available (it usually is)
openssl version

# Ensure the kernel headers and mokutil are installed
sudo apt update
sudo apt install build-essential linux-headers-$(uname -r) mokutil

Generating the MOK Key Pair

We will use openssl to generate a 2048-bit RSA key pair. You will be prompted to enter a strong passphrase. This passphrase protects your private key (MOK.priv) and is the source of all the frustration later on—we will need to temporarily disable it.

Important: Store your passphrase securely, as you will need it in the next steps.

If you already have a key pair at /etc/ssl/MOK.priv and /etc/ssl/MOK.pem you can skip this step.

# Create the MOK key pair, valid for 10 years (3650 days).
# We name the output MOK.pem as that is its actual content format.
openssl req -new -x509 -newkey rsa:2048 -keyout MOK.priv -out MOK.pem -days 3650 -subj "/CN=NVIDIA MOK Key/"

Moving Keys and Finalizing Setup

After generation, the keys are in your home directory. We will now move the keys to the secure, system-wide location (/etc/ssl/), ensure they have correct ownership, and then delete them from the home directory for security.

# Move the keys to /etc/ssl
sudo cp MOK.priv /etc/ssl/
sudo cp MOK.pem /etc/ssl/

# Ensure the private key has restrictive permissions (root owner, read-only)
sudo chown root:root /etc/ssl/MOK.priv
sudo chmod 400 /etc/ssl/MOK.priv

# DELETE THE KEYS FROM THE HOME DIRECTORY FOR SECURITY
rm MOK.priv MOK.pem

We now have the two critical files safely located:

/etc/ssl/MOK.priv: The Private Key (password protected).

/etc/ssl/MOK.pem: The Public Certificate (used for enrollment).

The Two-Part Problem: Signing and Format Errors

With the keys securely in /etc/ssl/, we encounter the reason this procedure requires manual intervention. If you were to try to install or sign a driver now (or if DKMS tries to do it automatically), the process would fail due to two independent, yet interconnected, bugs in the standard Linux toolchain:

Signing Failure (The Passphrase Bug)

The tool at the center of this failure is the sign-file script. This utility is distributed with the general Linux kernel headers (not just Ubuntu) and is responsible for adding cryptographic signatures to kernel modules. Therefore, this bug affects any Linux distribution relying on this toolchain.

The script is unable to correctly handle the passphrase protecting your MOK.priv file. When it tries to read the key, it crashes with a cryptic error related to OpenSSL’s file input:

- SSL error:FFFFFFFF80000002:system library::No such file or directory: ../crypto/bio/bss_file.c:67

This error is our primary obstacle. In the next step, we will design a secure workaround by temporarily unlocking the private key, thus preventing the sign-file script from crashing and allowing the modules to be signed.

I’ve reported this bug to the Ubuntu team at: Launchpad Bug #2119337

Enrollment Failure (The Format Conflict)

The mokutil utility, which we use later to enroll the key into the UEFI system, is extremely rigid. Even if we successfully sign the modules, mokutil demands that the public key be in the binary DER (Distinguished Encoding Rules) format.

Since our MOK.pem file is in the human-readable PEM format, mokutil will reject it, forcing us to perform an explicit conversion before the final enrollment.

The next major section will provide the multi-step solution to bypass the first problem: the signing failure caused by the protected private key and ZSTD compression.

The Core Fix – Signing the Modules

This is the multi-step process required to successfully sign the kernel modules, bypassing the limitations of the sign-file utility and the ZSTD compression of the kernel.

Workaround 1: Creating the Unlocked Private Key

To prevent the sign-file script from crashing due to its inability to handle the passphrase, we must temporarily create an unprotected copy of your private key (MOK.priv).Security Note: We create this unlocked key in /etc/ssl/ but you must delete it immediately after the signing process is complete.

# Back up the protected key (MOK.priv.bak)

sudo cp /etc/ssl/MOK.priv /etc/ssl/MOK.priv.bak

# Create the UNLOCKED key. You will be prompted for your MOK passphrase here.
sudo openssl rsa -in /etc/ssl/MOK.priv -out /etc/ssl/MOK_unlocked.priv

We now use /etc/ssl/MOK_unlocked.priv for signing.

Workaround 2: Handling ZSTD Compression and Signing

On modern Linux kernels (like 6.8.x), modules are compressed using ZSTD and named .ko.zst. The sign-file script only works on uncompressed files (.ko).We must find the target NVIDIA modules, loop through them, decompress them, sign them using our unlocked key, and then re-compress them.

Preparation: Identify the location of the NVIDIA modules installed by DKMS.

The correct directory can vary between Ubuntu releases. We must confirm the path where the proprietary kernel modules have been placed.

Diagnostic Check: Run this command to find the required files. The output line you want is the directory containing nvidia.ko.zst.

sudo find /lib/modules/$(uname -r) -name 'nvidia.ko.zst'

If the command above fails to return the proprietary module files, you may need to force a DKMS rebuild (e.g., sudo apt install --reinstall nvidia-driver-XXX).

Set the correct path based on the output above. (The most common path is shown below).

# Set a variable for the module directory (e.g., /lib/modules/6.8.0-xx-generic/updates/dkms)
NVIDIA_DIR="/lib/modules/$(uname -r)/updates/dkms"

# Check if the directory exists (optional verification step)
ls -al ${NVIDIA_DIR}

The Signing Loop:

Run this entire code block as a single operation. It finds all compressed NVIDIA modules, performs the necessary three-step transformation (decompress, sign, re-compress), and cleans up the temporary uncompressed files.

# This loop performs the full decompression, signing, and re-compression process
for MODULE_ZST in ${NVIDIA_DIR}/*.ko.zst; do
    MODULE_KO=${MODULE_ZST%.zst}
    
    echo "Processing: ${MODULE_ZST}"

    # 1. Decompress the ZSTD module to create the target .ko file
    sudo zstd -d "${MODULE_ZST}" -o "${MODULE_KO}"

    # 2. Sign the uncompressed .ko file using the UNLOCKED private key
    # MOK.pem contains the certificate corresponding to MOK_unlocked.priv
    sudo /usr/src/linux-headers-$(uname -r)/scripts/sign-file sha256 \
         /etc/ssl/MOK_unlocked.priv /etc/ssl/MOK.pem "${MODULE_KO}"

    # 3. Re-compress the now-signed .ko file back to .ko.zst, overwriting the original
    sudo zstd "${MODULE_KO}" -o "${MODULE_ZST}" --rm
done

Clean Up the Unlocked Key

Immediately after the loop completes successfully, you must delete the unprotected copy of your private key to restore security integrity.

# Remove the unprotected copy of the private key
sudo rm /etc/ssl/MOK_unlocked.priv

With the modules signed, we have successfully overcome the first major set of obstacles. The final step is key enrollment.

Step 3: Enrollment and Final Format Correction

The modules are now signed using your key. The final step is to instruct the UEFI system to trust your key by queuing the public certificate for enrollment. This step is complicated by the rigid input requirements of the mokutil utility.

The Final Conflict: PEM vs. DER

Your long-term certificate file (MOK.pem) is in the flexible, human-readable PEM (ASCII/Base64) format.The mokutil tool on your system specifically demands the public key input be in the DER (binary) format to successfully queue the key.If you attempt to import the key directly, it will fail:

Abort!!! /etc/ssl/MOK.pem is not a valid x509 certificate in DER format

The Necessary Conversion Workaround

We must use openssl again to convert the key to the binary DER format just for the enrollment command. We use a timestamp in the filename for easy identification of this temporary enrollment artifact.

# 1. Set a timestamp variable for the new, temporary filename
TS=$(date +%Y%m%d_%H%M)

# 2. Use openssl to read the PEM format (-inform PEM) and write the required DER format (-outform DER).
sudo openssl x509 -in /etc/ssl/MOK.pem -inform PEM -out /etc/ssl/MOK_$TS.der -outform DER

Queuing the Key for Enrollment

You can now use the properly formatted DER file to queue the key for enrollment

# Import the new, properly formatted DER file.
sudo mokutil --import /etc/ssl/MOK_$TS.der

STOP: This command will successfully execute and prompt you to set the One-Time Password. This is the password you will use in the next step when the system reboots. Store it securely!

System Reboot and UEFI Enrollment

Once the password is set, reboot the system to complete the enrollment process.

sudo reboot
  1. When the machine restarts, it will interrupt the boot sequence and show the MokManager blue screen.
  2. Select Enroll MOK.
  3. Select Continue and confirm the key fingerprint.
  4. You will be prompted to enter the One-Time Password you just created in the terminal.
  5. Once enrollment is complete, select Reboot.

After the system boots up, the final step is to verify that all modules are loading correctly.

Verification and Conclusion

After the successful reboot and MOK enrollment in the UEFI screen, your custom signing key is now trusted by the system. The final step is to verify that Secure Boot is active and that your signed NVIDIA modules are loading correctly.

Verification Checks

Run these commands to confirm success:

Confirm MOK Enrollment and Secure Boot Status

Check that the key has been successfully written to the database and that the operating system recognizes Secure Boot is active:

# Check if the public key is present in the database
mokutil --list-enrolled

# Confirm Secure Boot is active
mokutil --sb-state
  • Expected Output: mokutil --sb-state should return: SecureBoot enabled
  • Confirmation: The mokutil --list-enrolled output should show your CN=NVIDIA MOK Key certificate fingerprint.

Confirm NVIDIA Driver is Loading

If the verification steps above are successful, the signed kernel modules will now be allowed to load.

# Check if the kernel modules are loaded
lsmod | grep nvidia

# Check if the NVIDIA card is recognized and fully functional
nvidia-smi
  • Expected Output: Both commands must succeed. lsmod should list all nvidia modules (e.g., nvidia_drm, nvidia_uvm), and nvidia-smi should display the driver version and GPU status without error.

You should now clean up any DER certificates that you created for the MOK enrollment. They are based on the public PEM key and are no more secret than that file. However, it’s better practice to have one source of truth.

sudo rm /etc/ssl/MOK_*.der

Conclusion

The complex procedure of installing NVIDIA drivers under Secure Boot is now complete. You have successfully navigated and engineered workarounds for the three core defects in the Linux signing toolchain: the sign-file passphrase bug, the ZSTD compression conflict, and the mokutil format rigidity.

This solution was developed on an active test system and is confirmed to work across multiple environments, including LTS and latest release Ubuntu systems, hopefully demonstrating a robust and universal fix for this problem.

Filtering Characters in C# and Rust

I recently watched a video about a tool that Will Crichton, a researcher at Brown University, had created to help developers to understand Rust’s strict syntax. The motivation behind the tool was that Rust is notoriously difficult to learn because developers do not have an accurate mental model of how the Rust compiler restricts the use of variables. The tool aims to help with that by showing what is happening to variables in terms of permissions line by line in the program.

The tool is on the Brown University web site: https://cel.cs.brown.edu/aquascope/

I played around with some small Rust programs that I had written in the past to experiment with the language. Rust is a functional language, so it lends itself well to chaining functions together to make pipelines in a fluent syntax style. For example:

let s = s.chars().filter(|c| c.is_alphanumeric()).collect::<String>();

This takes a “String” called “s” and filters out any characters in the string that are not alphanumeric and collects them up as a string. For example, “abc*$%123” goes to “abc123”.

The Brown tool copes with that, but I quickly found that it was easier to split lines up to see where objects go out of scope, like the following:

let chars = s.chars();
let s = chars.filter(|c| c.is_alphanumeric()).collect::<String>();

Looking at the permissions of these lines in the tool, we can see where a path, such as “s” or “chars”, is initialized (the upwards arrow) and when it is no longer used (the downwards arrow). We can also see the changes to read, write and ownership permissions on each line.

The change that interested me most was the rightwards arrow on lines 4 and 5 for “chars”. This shows that “chars” is “moved” here and loses all its permissions. This surprised me because I had thought of “chars” as a collection of characters that I could filter potentially repeatedly.

For example, in C#, we just need one string as an input of a collection of characters. The “Where” extension method does not care that the string has been filtered once already.

const string input = "abc*$%123";

var alphaNum = input.Where(c => char.IsLetter(c) || char.IsNumber(c) ).ToArray();

var nonAlphaNum = input.Where(c => !char.IsLetter(c) && !char.IsNumber(c)).ToArray();

Console.WriteLine($"Alphanumeric characters: {new string(alphaNum)}");
Console.WriteLine($"Non-alphanumeric characters: {new string(nonAlphaNum)}");

In order to write something similar in Rust, we need to call “chars()” a second time as the first iterator has been “moved” when we ran filter on it:

let input = "abc*$%123";

let alpha_num_chars = input.chars();
let alpha_num: String = alpha_num_chars.filter(|c| c.is_alphanumeric()).collect();

// Note that we need to get a new iterator for the input chars here.
// The char iterator for alpha_num_chars was used when we filtered
// the alphanumeric chars above.
let non_alpha_num_chars = input.chars();
let non_alpha_num: String = non_alpha_num_chars
    .filter(|c| !c.is_alphanumeric())
    .collect();

println!("Alphanumeric characters: {}", alpha_num);
println!("Non-alphanumeric characters: {}", non_alpha_num);

I’m not sure that I see the Rust version as an improvement. The Rust code did force me to think about what objects needed to be created in order to achieve the filtering. In Rust, I need to explicitly create the character iterators for each filtering. In C#, this is handled for me. In the C# version, the “Where” extension method does need to iterate over the “IEnumerable<char>” for the “string”. There’s no magic to this; iterator objects may need to be created in order to range over the characters of the string. You can check out the reference source here:

https://github.com/microsoft/referencesource/blob/ec9fa9ae770d522a5b5f0607898044b7478574a3/System.Core/System/Linq/Enumerable.cs#L15

Of course, Rust advocates will point out that the C# version of the code is creating iterator objects that need to garbage collected at some unknown point later in time, which might not be acceptable.

I’d be grateful to hear any comments about which approach should be considered better.

Either way, I thank the researchers who created this tool that has demystified some of the frustrating error messages that Rust sometimes throws up in seemingly trivial code that should just work.

You can take a look at the code examples:

https://github.com/robert-impey/CodingExperiments/blob/02509bab31cb250baa1eb5341ee6ed7aa63b5ec2/dotnet/C-Sharp/DoubleSplit/Program.cs

https://github.com/robert-impey/CodingExperiments/blob/b9219bb334a3a1bb211a3ea366a54b3e276156f3/Rust/double_split/src/main.rs

The Beatles in The Lord of the Rings

Many years ago, when I was studying Artificial Intelligence at Birmingham University, I read about a project that the Beatles had proposed that was never completed. They wanted to make a film version of The Lord of the Rings, with Paul as Frodo, Ringo as Samwise, George as Gandalf and John as Gollum. What is more, they wanted Stanley Kubrick (John was a huge fan of 2001) to direct the movie.

Stanley Kubrick wasn’t interested, the Beatles split up, and the project never got off the ground.

At the time, I was wondering a lot about the question “Could a machine ever think?” Different philosophers put forward different answers to that question. Some dismissed the question as being as important as asking “Can submarines swim?” Others, notably proponents of the Turing Test, sought to answer the question by looking at the observable performance of the system. A milestone that I thought about was an AI system that could produce the film described above just from prompting. It seemed like science fiction fantasy at the time.

20 years later, and AI has come a very long way. In just a few minutes this morning, I was able to create some images using Hugging Face’s Stable Diffusion system purely from written prompts from my phone:

https://huggingface.co/spaces/stabilityai/stable-diffusion

John Lennon as Gollum
John Lennon as Gollum
Paul McCartney as Frodo Baggins
Paul McCartney as Frodo Baggins
Ringo Starr as Samwise Gamgee
Ringo Starr as Samwise Gamgee
George Harrison as Gandalf
George Harrison as Gandalf

It’s not an epic in the style of Stanley Kubrick. Nor has it generated a Beatles-esque soundtrack. However, the power of these AI systems is astounding.

What I learned rewriting old Perl scripts in Go

As part of my project to learn the Go programming language, I decided to rewrite some of my old Perl scripts in the newer language to see what was better, if anything was worse or if things stayed the same.

The scripts are not very glamorous, but are useful for my set up. One is for generating scripts that wrap around rsync in order to keep two directories in synch. The other (which is closely related) is for keeping track of which files have been marked for deletion and keeps deleting them if they reappear. Once one starts to copy files back and forth between directories, deleting files becomes a little bit complicated as the file you delete will keep reappearing unless you delete it everywhere. The script I wrote them before Dropbox and the like had come on the scene. I keep them around as I don’t like to have the only copy of my photos and videos in a folder managed by someone else. They are also useful for folders that have too much content to be stored practically in Dropbox, like virtual machine files, and synching folders on servers via SSH.

I have been meaning to update the scripts and change their behaviour for a while, so a rewrite is a good time to ditch some obsolete features. The synch script generator used to be able to generate batch files to run on Windows. Now, it just creates bash scripts. This is fine (for me) as, on Windows, I use Cygwin for rsync, so bash is not a problem for me as a dependency.

Another change is that the script generator used to silently skip generating a script if a file was in its destination. The thinking was that the generated scripts could be considered scaffolding for more capability that could be added by adding to or amending the scripts. The script should not overwrite these changes. Experience, here and elsewhere, has taught me that this is a nightmare to work with. Generated files should be regeneratable at any time. In light of this, the generated scripts are marked with a warning comment at the top saying that they have been autogenerated and are blasted out of the way when the program is run again, potentially as part of a scheduled task.

The script generation program is at:

https://github.com/robert-impey/generate-synch-scripts

The second program is for making sure that files stay deleted when two folders are synched as described above. This had been at

https://github.com/robert-impey/stay-deleted

However, as the project grew and I need to move code to more than one file I learned that package names in Go should not contain punctuation, so I started a fresh project and moved my code there:

https://github.com/robert-impey/staydeleted

My new version of the program is working correctly. I’ve also added a few new features like deleting old metadata files and an option to run repeatedly at random times, which is useful for running as a scheduled task.

The most immediate advantage that I have found for this script is the ease of distributing a binary generated by the Go compiler. The nature of the software requires that the program runs on every computer in the system, for my set up that includes Windows, macOS and Linux. Getting a perl script with a few library dependencies to run on all those computers was a pain. With Go, it’s been trivial so far.

In order to have a more modern command-line interface, my program now uses spf13’s Cobra library:

https://github.com/spf13/cobra

This has forced me to reorganize my code to some extent. This has been a good thing. However, I’m still very much at the beginning of my Go learning journey. Whilst the program works; the code is a bit of a mess. I’m not sure how to apply the clean code principles (such as SOLID) that I use in my day job writing C# to Go. Perhaps this is one of the main advantages of aiming to be a polyglot developer. Everyone should aim to write readable code in every language. We discuss and come to an agreement about design principles to do with how to use the language’s features in order to make code more readable. When one moves to a new language, you might not know how the language goes about implementing those features or those features don’t exist. What happens then to those design principles? Can they be reformulated for the new language?

Stress Testing Algorithmic Code

I keep a “To Do” list stored in a text file. I add sub-tasks to tasks by putting them on the line below the task at a greater depth of indentation. This works for me as I find that whenever I look at any task, I can always think of ways to break it down further. Also, I get to see everything in one place.

A few years ago, I decided to write a tool to sort my “To Do” list:

https://github.com/robert-impey/tree-sorter

The complex part was parsing tree structures of arbitrary depth and sorting each tree and subtree independently.

For example,

II Animals
  2 Dogs
  3 Cats
  1 Fish
I Plants
  b Nettles
  c Oak
  a Grass

becomes

I Plants
  a Grass
  b Nettles
  c Oak
II Animals
  1 Fish
  2 Dogs
  3 Cats

This works fine for my tasks. My list is saved in a file and a scheduled task sorts it periodically.

However, one annoyance was that if the file was was already in order, the program would sort and write out anyway. Another problem, was that I was never very pleased with the algorithm that I wrote. Although the performance was acceptable for the 300 odd lines of my file, I suspect that I can do better. I already had in place a range of unit tests and sample files as fixtures. I could just start by trying to improve the data structures and algorithm at the heart of the program. However, I want to be really sure that I don’t introduce a regression for a particularly tricky tree that I hadn’t thought of.

Fortunately, the input and the output of the algorithm are easy to describe. The input is any tree structure in space indented lines in a text file; the output is those lines in order. I decided to add a stress test to the program. The test would randomly generate trees of a given size and depth. The sorting code would then attempt to put them into order. If the result is not in order, the program halts and prints out the offending input and output. Otherwise, the program would keep looping round (generating, sorting and checking trees) until I killed the process.

while True:
    random_tree_lines = generate_random_tree_lines(
        args.Depth,
        args.Items,
        args.Length,
        args.Alphabet)

    tree = lines_to_tree(random_tree_lines)

    lines = tree.get_lines()

    if not are_lines_sorted_tree(lines):
        print('A tree was not sorted correctly')

        print('Input')
        for line in random_tree_lines:
            print(line)

        print('Output')
        for line in lines:
            print(line)

        break q

The complete listing is at:

https://github.com/robert-impey/tree-sorter/blob/master/stresstest.py

Such a stress test is intended to be a supplement to unit tests. If a tree is not sorted correctly, it should be simplified and added to the unit test fixtures. Then, once the code has been fixed to deal with the tricky input, we know that we can avoid regressions. Generally, random generators are less forgiving than developers when it comes to coming up with tricky inputs.

This stress test will keep running forever if left uninterrupted. Typically, if there is an error anywhere in a system of this level of complexity, it will be found within seconds. The stress test didn’t find an error conditions in the existing code. However, it did take a few iterations to iron out a few off-by-one errors in my code for testing that a tree was in order! This helped me build up the unit tests for that part of the program.

As well as allowing me to make changes to the algorithm at the heart of the program, having a function that tells me if a tree is in order or not allows me to skip overwriting the existing file if the file is already in order:

lines = get_lines(file_name)

if in_place and are_lines_sorted_tree(lines):
    print('In place sorting requested but already sorted.')
else:
    # Sorting work...

The complete listing is here:
https://github.com/robert-impey/tree-sorter/blob/master/treesorter.py

Make Turning Windows Off and On Again Great Again

There’s a joke about all Windows related problems being solvable by turning the computer off and on again. It’s one of the things that works most reliably about the OS. Well, even this has been broken by Microsoft in the Windows 10 Fall Creators Update.

When you get to the point where you have more than a dozen virtual desktops running with many different programs, your computer (not to mention your brain) will start to get overloaded. At times like these, I just want to hit refresh (to coin a phrase…) and get back to an unmussed system. However, a new “feature” in the Fall Creators Update of Windows 10 will try to reopen as many of the programs that you had running beforehand as possible. Not all programs will get restarted. Tiny programs like Notepad++ stay unloaded, but bloated behemoths that hang for 30 seconds to a minute to load (like Excel and Visual Studio) get restarted, maybe with the files that you had opened, maybe not. If you were using virtual desktops beforehand and had carefully separated your programs by task, all the programs will be in the first one but you will still have several empty and useless virtual desktops open. Instead of getting a fresh start on a clear desktop, you are left waiting for programs to load and needed to close all the virtual desktops. Unfortunately, there’s no setting to just turn off this rather half-baked behaviour.

However, a little PowerShell can reduce the pain and shutdown the computer more thoroughly.

I don’t want to accidentally trigger this, so my script starts with a confirmation:

Write-Output "This will close all your virtual desktops and shutdown the computer."
$Confirm = Read-Host "Hit Y to confirm."
if ($Confirm.ToLower() -ne 'y')
{
    Write-Output "Doing nothing"
    exit
}

Write-Output "Shutting down..."

Closing all the other virtual desktops can be achieved with by wrapping around MScholtes’ VirtualDesktop:

while ($true)
{
    $CountCommand = "$($VirtualDesktopExe) /C"
    $CountOutput = iex $CountCommand
    if ($CountOutput -match 'Count of desktops: (\d+)')
    {
        $Count = $Matches[1]

        if ($Count -gt 1)
        {
            Write-Output "You still have $($Count) virtual desktops."
            iex "$($VirtualDesktopExe) /R"
        }
        else
        {
            Write-Output "Only one virtual desktop at this point"
            break
        }
    }
    else
    {
        Write-Error "Unable to parse result of command '$($CountCommand)': '$($CountOutput)'"
        exit
    }
}

This simply invokes the program with the “/C” flag (count) then calls the program with “/R” (remove) until only one virtual desktop remains.

After that, the script just invokes the old fashioned shutdown command from Ramesh Srinivasan’s article above about this new feature.

shutdown.exe /s /t 0

On my desktop, I have a link to a script that invokes the PowerShell script with the location of the VirtualDesktop.exe file on my machine:

PowerShell -command "F:\Robert\Dropbox\local-scripts\_Common\CloseVirtualDesktopsAndShutdown.ps1 -VirtualDesktopExe F:\Robert\Dropbox\executables\Windows\x64\VirtualDesktop.exe"

Now I know that I will get a fresh start when I turn on my computer again. I’m not really sure why this isn’t the default behaviour.