Execute a drush command programmatically

Submitted by editor on Thu, 09/29/2016 - 15:49
Question

How to execute a drush command programmatically ?

Methodes:

drush_invoke (For the current site)
drush_invoke($command, $arguments = array());

drush_invoke_process
This creates a new process in a new Drupal instance. There for you must specify the site alias.
drush_invoke_process($site_alias_record, $command_name, $commandline_args = array(), $commandline_options = array(), $backend_options = TRUE);

Example 1. Enable a Module/Feature and Revert all features.

$site = drush_sitealias_get_record('@mysite');
drush_invoke_process($site, 'pm-enable', array("features_dependencies","-y"));
drush_invoke_process($site, 'features-revert-all', array("-y","--force"));

//OR for the current site:
drush_invoke_process('@self', 'features-revert-all', array("-y","--force"));
 

 

Example 2. Run a drush command at  the installation of a module. 

function mymodule_install() {
    // clears the 'all' cache for current web site
    //Methode 1.
    drush_invoke('cache-clear', 'all');
    
    Or

    //Methode2.
    $site = drush_sitealias_get_record('@mysite');
    drush_invoke_process($site, 'cache-clear', array('all'));
}

Add new comment

CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image.