Skip to content

Instantly share code, notes, and snippets.

@HauptJ
Created November 22, 2025 22:22
Show Gist options
  • Select an option

  • Save HauptJ/7aa32304fba4c8f01e42abbae0595910 to your computer and use it in GitHub Desktop.

Select an option

Save HauptJ/7aa32304fba4c8f01e42abbae0595910 to your computer and use it in GitHub Desktop.
PowerShell script to configure WSL and install distros
#Requires -RunAsAdministrator
param (
[string[]] $optDistros = @("Ubuntu-24.04"),
[string[]] $optConfigs = @("[wsl2]", "networkingMode=mirrored")
)
function updateWSLConfig {
Param(
[Parameter(Mandatory=$true)]
[string[]] $optConfigs
)
try {
# configure WSL for user
# set config file path
$filePath = "C:\users\$env:USERNAME\.wslconfig"
Write-Output $filePath
# check if file already exists if so clear it
if(Test-Path $filePath){
try {
# Try shutting down WSL
Write-Output "Shutting down WSL"
wsl --shutdown
} catch {
Write-Output "Failed to shutdown WSL"
}
Write-Output "$filePath exits - clearing"
Clear-Content -Path $filePath
} else {
# create blank config file
Write-Output "$filePath does not exist - creating"
New-Item -Path $filePath -ItemType File
}
# write config options to config file
foreach($config in $optConfigs){
Add-Content -Path $filePath -Value $config
Write-Output $config
}
} catch {
Write-Output "An error occurred"
if($Error.Count -gt 0){
Write-Output "Errors thrown: " $Error.Count
foreach($err in $Error){
Write-Output "Error: $err"
}
}
Exit -1
}
}
function installWSLDistros {
Param(
[Parameter(Mandatory=$true)]
[string[]] $optDistros
)
try {
try {
# Try shutting down WSL
Write-Output "Shutting down WSL"
wsl --shutdown
} catch {
Write-Output "Failed to shutdown WSL"
}
# Update WSL
write-Output "Updating WSL"
wsl --update
# Get list of installed Distros - if any
$installedDistros = wsl -l -q
# Install Distros
foreach($distro in $optDistros){
# check if Distro is already installed
if($installedDistros -contains $distro){
Write-Output "Distro: $distro is already installed"
} else {
Write-Output "Installing Distro: $distro"
wsl --install $distro
}
}
} catch {
Write-Output "An error occurred"
if($Error.Count -gt 0){
Write-Output "Errors thrown: " $Error.Count
foreach($err in $Error){
Write-Output "Error: $err"
}
}
Exit -1
}
}
try{
updateWSLConfig -optConfigs $optConfigs
installWSLDistros -optDistros $optDistros
#TODO
# HyperV firewall configuration
Exit 0
} catch {
Write-Output "An error occurred"
if($Error.Count -gt 0){
Write-Output "Errors thrown: " $Error.Count
foreach($err in $Error){
Write-Output "Error: $err"
}
}
Exit -1
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment