Creating a Ubuntu Server as a guest OS on Hyper-V Host with Secure Boot via Powershell

I was recently curious about Secure Boot, a mechanism that starts the bootloader only if the bootloader’s signature has maintained integrity, assuring that only approved components are allowed to run. I was pleasantly surprised to find that it was supported on most Linux distributions. The important take away here is to configure the VM to use the Microsoft UEFI Certificate Authority.

If you have an existing VM, you can enable it by

Set-VMFirmware TestVM -SecureBootTemplate MicrosoftUEFICertificateAuthority

If you want to start from scratch you can follow the script below, it assumes that you've already created a virtual switch and have downloaded a copy of Ubuntu Server

Create and configure

# VM creation
$vmName = "UBUSRV";
$vmNewDiskPath = "F:\HyperV\Virtual Hard Disks\UBUSRV.vhdx";
$vmNewDiskSize = 20GB;
$vmPath = "F:\HyperV\Virtual Machines";
$vmGeneration = 2;
$vmBootDevice = "VHD";
$vmSwitchName = "MyVirtualSwitch"; # To find existing switches run, Get-VMSwitch | ft
$vmDvdDrivePath = "C:\Users\Frank\Downloads\ubuntu-18.04.1.0-live-server-amd64.iso"

$vmFirmwareEnableSecureBoot = "On"; # Turn off if you trust and/or image isn't supported.
$vmFirmwareSecureBootTemplate = "MicrosoftUEFICertificateAuthority";

$vmProcessorCount = 4;
$vmMemoryStartUpBytes = 1GB;
$vmMemoryMinimumBytes =  500MB;
$vmMemoryMaximumBytes =  3GB;
$vmDynamicMemoryEnabled = $true;

New-VM -Name $vmName -BootDevice $vmBootDevice -NewVHDPath $vmNewDiskPath -Path $vmPath -NewVHDSizeBytes $vmNewDiskSize -Generation $vmGeneration -SwitchName $vmSwitchName
Set-VMFirmware $vmName -EnableSecureBoot $vmFirmwareEnableSecureBoot -SecureBootTemplate $vmFirmwareSecureBootTemplate
Set-VMProcessor $vmName -Count $vmProcessorCount
Set-VMMemory $vmName -DynamicMemoryEnabled $vmDynamicMemoryEnabled -MinimumBytes $vmMemoryMinimumBytes -StartupBytes $vmMemoryStartUpBytes -MaximumBytes $vmMemoryMaximumBytes
Add-VMDvdDrive $vmName -Path $vmDvdDrivePath # To eject run Remove-VMDvdDrive $vmName

Debug and clean up

# Debugging
Get-VMFirmware $vmName | fl
Get-VMProcessor $vmName | fl
Get-VMMemory $vmName | fl
Get-VMDVDDrive $vmName | fl 

# Clean up
Remove-VM -Name $vmName -Force
Remove-Item $vmNewDiskPath -Force

https://www.ubuntu.com/download/server

https://docs.microsoft.com/en-us/windows-server/virtualization/hyper-v/supported-linux-and-freebsd-virtual-machines-for-hyper-v-on-windows
https://docs.microsoft.com/en-us/windows-server/virtualization/hyper-v/supported-ubuntu-virtual-machines-on-hyper-v
https://docs.microsoft.com/en-us/windows-server/virtualization/hyper-v/what-s-new-in-hyper-v-on-windows#BKMK_linux