docker commands | Delete all images in Powershell | Delete images in cmd | Search

This Windows batch script iterates through a list of all Docker container IDs and forcefully removes each container.

Run example

npm run import -- "Delete containers in cmd"

Delete containers in cmd

FOR /f "tokens=*" %i IN ('docker ps -a -q') DO docker rm %i

What the code could have been:

bash
#!/bin/bash

# Function to remove all stopped containers
remove_stopped_containers() {
  # Use docker ps with -a and -q flags to get a list of stopped container IDs
  stopped_containers=$(docker ps -aq)

  # Iterate over each stopped container and remove it
  for container in $stopped_containers; do
    # Use docker rm with -f flag to force removal of the container
    docker rm -f "$container"
  done
}

# Call the function to remove stopped containers
remove_stopped_containers

This code snippet forcefully removes all Docker containers, both running and stopped.

Here's a breakdown:

  1. FOR /f "tokens=*" %i IN ('docker ps -a -q'):

  2. DO docker rm %i:

In essence, the code does the following:

  1. Gets a list of all Docker container IDs.
  2. Loops through each container ID.
  3. Removes each container using the docker rm command.

Let me know if you have any other code snippets you'd like me to explain!