blog-banner

Creating a Custom Drush Command

  • Drupal 6
  • Drupal 7
  • Drupal Planet
  • Drush

Drush Commands

 
No Drupal Developer needs an introduction about Drush. The power and features of Drush have made the job easier for many developers. Drush by default has a list of commands that we can make use of, the entire list can be seen here. But apart from that, the Drush does has the feature to allow custom commands.
 
These custom commands can be used as per our needs and scenarios. In my case, I had the need to list the users on the site using a Drush command. To create a custom Drush command we need to create a custom module and then create a new file in the module - [module-name].drush.inc. We will make use of the hook_drush_command to create a new Drush command.
 
  1. /**
  2.  * Implementation of hook_drush_command().
  3.  */
  4. function mymodule_drush_command() {
  5.   $items = array();
  6.   // Name of the drush command.
  7.   $items['list-site-users'] = array(
  8.     'description' => 'Print the list of users in the site',
  9.     'callback' => 'drush_get_site_users',
  10.   );
  11.   return $items;
  12. }
  13.  
  14. function drush_get_site_users() {
  15.   $query = db_select('users', 'u');
  16.   $query->fields('u', array('name'));
  17.   $result = $query->execute();
  18.   while($record = $result->fetchAssoc()) {
  19.        print_r($record['name']);
  20.   }
  21. }
 
Now go to the command line and run the below command to list the users present on the drupal site.
drush list-site-users
The custom Drush command can be used in any kind of scenario. Forget not to enable the module, before using the custom Drush command.

 

Get awesome tech content in your inbox