Skip to content

Instantly share code, notes, and snippets.

@nopeless
Last active September 28, 2025 09:37
Show Gist options
  • Select an option

  • Save nopeless/a22af0a933731f56543906d6a94f3e88 to your computer and use it in GitHub Desktop.

Select an option

Save nopeless/a22af0a933731f56543906d6a94f3e88 to your computer and use it in GitHub Desktop.
# Spawns docker containers as lightweight VMs
# very convenient optionless
function dvm {
param (
[Parameter(ValueFromRemainingArguments=$true)]
[string[]]$args
)
$ErrorActionPreference = "Stop"
$selfLabel = "dvm"
if (-not (Test-Path \\.\pipe\docker_engine)) {
& docker desktop start
}
if (-not $args) {
docker container ls --filter "label=$selfLabel" --all --format "table {{ .Image }}\t{{ .Names }}\t{{ .State }}\t{{ .RunningFor }}"
return
}
$arg0 = $args[0]
if ($arg0[0] -eq "-") {
$toRemove = (docker container ls --filter "label=$selfLabel" --all --format "{{ .Names }}") | Where-Object { $_ -like $arg0.Substring(1) }
if ($toRemove) {
docker container rm --force $toRemove
}
return
}
$containers = & docker container ls --filter "label=$selfLabel" --all --format "{{ .Names }}\t{{ .State }}\t{{ .Image }}"
$shorthand = $arg0.Substring(0, 2).ToLower()
$dupids = @()
foreach ($line in $containers) {
$name, $state, $image = $line -split "`t"
if ($name -eq $arg0) {
$ident = "${name} + $image"
if ($state -ne "running") {
Write-Host -ForegroundColor Magenta "> $ident - starting"
$null = docker container start $name
} else {
Write-Host -ForegroundColor Magenta "> $ident"
}
docker container exec --interactive --tty $name bash --login
$ps = docker container exec $name find /proc -regex '/proc/[0-9]+'
if ($ps[0] -eq "/proc/1" -and $ps.Length -le 2) {
$null = docker container kill $name
Write-Host -ForegroundColor Magenta "< $ident - stopped"
} else {
Write-Host -ForegroundColor Magenta "< $ident - $($ps.Length - 2) processes remaining"
}
return
}
if ($name -match "^$shorthand(\d+)$") {
$dupids += [int]$Matches[1]
}
}
if ($arg0 -match "^\w\w\d+") {
throw "No container name matching $arg0"
return
}
$id = 0
while ($dupids -contains $id) {
$id++
}
$name = $shorthand + $id
$hostname = $name + "--" + $arg0 -replace "\W", "-"
$null = docker container create `
--label $selfLabel `
--interactive --tty --network host `
--hostname $hostname --name $name `
$arg0 `
sleep infinity
Write-Host -ForegroundColor Magenta $Name
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment