Skip to content

Instantly share code, notes, and snippets.

@Spongman
Last active October 31, 2024 03:01
Show Gist options
  • Save Spongman/92474f44d8ee655c5015a6adc75b0e11 to your computer and use it in GitHub Desktop.
Save Spongman/92474f44d8ee655c5015a6adc75b0e11 to your computer and use it in GitHub Desktop.
param (
# DockerHub image name passed as a parameter (required)
[Parameter(Mandatory=$true)][string]$dockerImage,
[string]$wslDistroName = ($dockerImage -replace ":[^:]+$", "").Replace("/", "_"),
[string]$arch = "amd64",
[switch]$Force
)
$ErrorActionPreference = 'Stop'
# Check if WSL is installed
if (-not (wsl --list)) {
echo "WSL is not installed."
exit 1
}
# Check if Docker Desktop is running
$pipePath = "\\.\pipe\dockerDesktopLinuxEngine"
if (-not (Test-Path $pipePath)) {
echo "Docker Desktop is not running."
exit 1
}
# Check if the WSL distribution already exists
$existingDistros = wsl --list --quiet
if ($existingDistros -contains $wslDistroName) {
if (-not $Force) {
echo "A WSL instance with the name '$wslDistroName' already exists. Use -Force to delete it first."
exit 1
}
wsl --unregister $wslDistroName
}
# Ensure the Virtual Machines directory exists
$basePath = "$env:USERPROFILE\Virtual Machines"
if (-not (Test-Path -Path $basePath)) {
mkdir $basePath | Out-Null
}
# Ensure the distro directory exists
$importPath = "$basePath\$wslDistroName"
if (-not (Test-Path -Path $importPath)) {
mkdir $importPath | Out-Null
}
$downloadPath = "$env:TEMP\$wslDistroName-layer.tar" # Temporary path for the tar file
$currentUser = ($env:USERNAME).ToLower()
# download / extract the docker layer tar
docker pull --platform linux/$arch $dockerImage
docker create --name wsl-import -it $dockerImage
docker export --output="$downloadPath" wsl-import
docker container rm -f wsl-import
# import the wsl instance
wsl --import "$wslDistroName" "$importPath" "$downloadPath" --version 2
rm $downloadPath
$wslConf = @"
[user]
default = $currentUser
[time]
useWindowsTimezone = false
"@ -replace "`r`n", "`n"
$sudoer = @"
Defaults:$currentUser !requiretty
$currentUser ALL=(ALL) NOPASSWD: ALL
"@ -replace "`r`n", "`n"
# setup the default user
wsl -d $wslDistroName --user root -- bash -c "useradd -m -s /bin/bash --system $currentUser ; echo -e '$wslConf' > /etc/wsl.conf ; mkdir -p /etc/sudoers.d ; echo -e '$sudoer' > /etc/sudoers.d/10-$currentUser"
wsl --terminate $wslDistroName
echo ""
echo "to start: wsl -d $wslDistroName"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment