2

I have used hook_drush_command to create a new drush command. This is my custom code for creating drush command.

/**
 * Implementation of hook_drush_command().
 */
function mymodule_drush_command() {
  $items = array();
  // Name of the drush command.
  $items['list-site-users'] = array(
    'description' => 'Print the list of users in the site',
    'callback' => 'drush_get_site_users',
  );
  return $items;
}

function drush_get_site_users() {
  $query = db_select('users', 'u');
  $query->fields('u', array('name'));
  $result = $query->execute();
  while($record = $result->fetchAssoc()) {
       print_r($record['name']);
  }
}

After this I have exceuted drush cc all and drush cc drush for clearing drush. Then I have executed my custom drush command drush list-site-users command, but it is throwing the below error.

The drush command 'list-site-users' could not be found. Run drush cache-clear drush to clear the commandfile cache if you have installed new extensions.

My drush version is 5.10.0

  • This should go in the module_name.drush.inc file. In case someone is looking for a Drupal 8 solution this is how I did it. – Nicolas Pinos Mar 25 '18 at 1:10
6

Try the following:

/**
 * Implements hook_drush_command().
 */
function mymodule_drush_command() {
  $items['list-site-users'] = array(
    'description' => 'Does a database cleanup.',
    'examples' => array(
      'list-site-users' => 'Retrieve list for all users',
    ),
    'aliases' => array('lsu'),
  );
  return $items;
}

function drush_mymodule_list_site_users() {
  $query = db_select('users', 'u');
  $query->fields('u', array('name'));
  $result = $query->execute();
  while($record = $result->fetchAssoc()) {
       print_r($record['name']);
  }
}

NOTE: Make sure you write the above code in mymodule.drush.inc file of any module. Clear the cache and your drush command should work.

  • It works after placing in mymodule.drush.in file. before I have plalced in my custom module – Vamsi Nov 24 '15 at 8:08
  • 2
    +1 for adding mymodule in the callback name. It is important to avoid conflicts with other modules. – kiamlaluno Nov 24 '15 at 8:11
3

I have made a mistake. For creating custom drush command we have to place code inside the module.drush.inc. I have placed the code inside my custom module. After placing the code inside module.drush.inc it works fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.