Backend and Infrastructure

Create a Custom Drush Command for Drupal 8, 9, and 10

Creating a custom Drush command requires creating a PHP class that Drush can find with annotated methods and metadata about each custom command. You'll create a file that tells Drush where to find the command class and any services to inject into it. You'll also modify the project's composer.json to tell Drush what versions of Drush the command is compatible with.

Custom Drush commands are a great way to expose your custom module's features to help automate these tasks and allow users to perform them as background processes. They can also provide a more efficient way to execute PHP code that takes a long time and is prone to timing out when run via the web server.

Depending on your use-case it can also be more efficient to create a custom Drush command to execute your logic instead of coding a complete UI. For example, if all the command needs to do is generate a CSV list it might take less effort to write a Drush command and pipe the output to a file than to create a UI that generates a file and prompts the user to download it.

In this tutorial we'll:

  • Declare a new custom Drush command inside a custom module
  • Make our custom Drush command output a list of all the blocked users on the site
  • Verify our new command is working

By the end of this tutorial you should understand how to create a custom Drush command that returns a list of blocked users.