Create a Drush command for bulk Drupal password resets
Large Drupal sites often accumulate user accounts for staff, contractors, clients and automated services. When credentials expire or a leak affects one account type, administrators need a repeatable bulk password reset instead of opening every user form. A custom Drush command makes the operation fast, filterable and repeatable from the command line.
This guide targets Drupal 10 and 11 with Drush 11 or 12. It creates a small module command that selects active users, applies a temporary password and forces a change at next login. The examples use a narrow role or explicit UID list, support a dry run, and keep the password out of command-line history.
Prepare a custom Drupal module
Start with a dedicated module rather than placing command code in sites/default. Use bulk_password_reset as the machine name, create src/Drush/Commands/BulkPasswordResetCommands.php, and keep the implementation in version control. Install a compatible Drush release with Composer if the project does not already include it, then confirm the site bootstraps with drush status.
The module can stay deliberately small. Its info.yml only needs the following metadata; the service definition and command class come later.
name: 'Bulk Password Reset'
type: module
description: 'Provides a Drush command for controlled password resets.'
core_version_requirement: ^10 || ^11
Define the reset behaviour
Decide whether “reset” means setting a shared temporary password, generating one unique password per person, or issuing one-time login links. This implementation sets one temporary password and resets the account’s last-login marker, so each user must choose a new password after signing in. A shared credential still permits brief impersonation, so use it only for a controlled group and never for privileged accounts without additional review.
Choose the smallest practical audience. Exact UIDs are safest; a role machine name is convenient for repeated batches; --all is an explicit last resort. For Australian organisations, the blast radius can be regulatory as well as operational. Many are covered by the federal Privacy Act and Australian Privacy Principles, while NSW health services must also consider state privacy and health-records rules. Document approval and avoid blanket resets. Changing a password does not reliably terminate every existing session, so invalidate sessions separately after a suspected compromise.
Handle hashing and account selection
Drupal’s User::setPassword() accepts the plain-text value and user storage hashes it when the entity is saved. Do not hash it yourself as well, or the password may be stored as a hash of a hash. Setting setLastLoginTime(0) on the same user object triggers Drupal’s next-login password-change flow; it avoids the extra save associated with calling user_pass_reset() separately.
The query should be deterministic: filter on active status, apply role or UID conditions, sort the IDs, and apply the limit before loading full user entities. A role and UID can be combined, in which case both must match. Drupal stores timestamps in UTC, while Sydney and Melbourne move between AEST and AEDT and Perth remains on UTC+8, so record reset times in UTC and state the local Australian offset.
Implement the Drush command class
The command supports role, UID, limit and dry-run options. --all must be supplied when neither a role nor an explicit UID list is present. Only active accounts are selected, preventing blocked users from being reset accidentally.
<?php
declare(strict_types=1);
namespace Drupal\bulk_password_reset\Drush\Commands;
use Drush\Attributes as CLI;
use Drush\Commands\DrushCommands;
use Drupal\Core\Entity\EntityTypeManagerInterface;
final class BulkPasswordResetCommands extends DrushCommands
{
private ?string $role = NULL;
private array $uids = [];
private bool $all = FALSE;
private int $limit = 0;
private bool $dryRun = FALSE;
public function __construct(
private EntityTypeManagerInterface $entityTypeManager,
) {
}
#[CLI\Command(
name: 'users:bulk-password-reset',
aliases: ['ubr'],
description: 'Reset passwords for selected Drupal users.',
)]
public function bulkPasswordReset(): void
{
if (!$this->all && $this->role === NULL && !$this->uids) {
throw new \InvalidArgumentException(
'Use --role, --uid or --all.'
);
}
if ($this->limit < 0) {
throw new \InvalidArgumentException(
'--limit cannot be negative.'
);
}
$storage = $this->entityTypeManager->getStorage('user');
$query = $storage->getQuery()
->accessCheck(FALSE)
->condition('status', 1);
if ($this->role !== NULL) {
$query->condition('roles', $this->role);
}
if ($this->uids) {
$query->condition('uid', $this->uids, 'IN');
}
$ids = array_values($query->execute());
sort($ids, SORT_NUMERIC);
if ($this->limit > 0) {
$ids = array_slice($ids, 0, $this->limit);
}
if (!$ids) {
$this->io()->warning('No matching active users.');
return;
}
if ($this->dryRun) {
foreach ($ids as $id) {
$user = $storage->load($id);
$this->io()->text(sprintf(
'UID %d: %s',
$id,
$user?->getAccountName() ?? 'unknown'
));
}
$this->io()->success(sprintf(
'Dry run: %d account(s) match.',
count($ids)
));
return;
}
$password = getenv('DRUPAL_BULK_TEMP_PASSWORD');
if (!is_string($password) || $password === '') {
throw new \RuntimeException(
'Set DRUPAL_BULK_TEMP_PASSWORD first.'
);
}
$changed = 0;
foreach ($storage->loadMultiple($ids) as $user) {
$user->setPassword($password);
$user->setLastLoginTime(0);
$user->save();
$changed++;
}
$this->io()->success(sprintf(
'Reset %d account(s).',
$changed
));
}
#[CLI\Option(name: 'role', description: 'Role machine name.')]
public function optionRole(?string $value): void
{
$this->role = $value;
}
#[CLI\Option(name: 'uid', description: 'Comma-separated user IDs.')]
public function optionUid(?string $value): void
{
$this->uids = $value === NULL ? [] : array_values(array_filter(
array_map('intval', explode(',', $value)),
static fn (int $id): bool => $id > 0
));
}
#[CLI\Option(name: 'all', description: 'Allow all active users.')]
public function optionAll(bool $value): void
{
$this->all = $value;
}
#[CLI\Option(name: 'limit', description: 'Maximum accounts to reset.')]
public function optionLimit(int $value): void
{
$this->limit = $value;
}
#[CLI\Option(name: 'dry-run', description: 'Show matches without changing them.')]
public function optionDryRun(bool $value): void
{
$this->dryRun = $value;
}
}
The temporary password comes from DRUPAL_BULK_TEMP_PASSWORD, keeping it out of Drush’s arguments and shell history. Use a long random value from an approved secret manager, and clear the environment variable after the operation.
Register and run the command
Register the class as a Drupal service with the drush.command tag. This tag makes Drush discover the command methods provided by the module.
services:
bulk_password_reset.commands:
class: Drupal\bulk_password_reset\Drush\Commands\BulkPasswordResetCommands
arguments:
- '@entity_type.manager'
tags:
- { name: drush.command }
Rebuild the cache, install the module and confirm that the command is available. Before any live run, check the site alias, database and URI with drush @environment status. A site hosted in a Sydney or Melbourne region can still use an alias pointing at a staging database.
drush cache:rebuild
drush pm:install bulk_password_reset -y
drush @staging users:bulk-password-reset --role=content-editor --limit=50 --dry-run
drush @prod users:bulk-password-reset --role=content-editor --limit=50
The live command requires DRUPAL_BULK_TEMP_PASSWORD to be present in the environment. Role selectors use machine names such as content-editor, not translated labels.
Test the reset safely
Test against a cloned database containing one account in the target role, one account in another role and one blocked account. Run the dry command first and compare its UIDs with the approved list. After a controlled live run, confirm that the target user can sign in, must replace the temporary password and cannot reach an unrelated role. The blocked account should remain excluded.
Keep a database backup, but treat it as sensitive personal information. A password cannot be recovered after hashing, so recovery depends on a tested restore or another authorised reset. Record the operator, selected UIDs, account count, UTC timestamp and local AEST/AEDT offset without recording the temporary password. This is particularly useful when an Australian support team is distributed across Brisbane, Sydney and Perth.
Compare methods and operational controls
A custom Drush command suits repeatable administrative batches; the alternatives cover smaller or more security-sensitive operations.
| Method | Speed | Forces a new password | Audit trail | Best fit |
|---|---|---|---|---|
| Custom Drush command | High | Yes, through the next-login flow | Drush transcript plus explicit operator log | Repeatable controlled batches |
| Drupal admin user form | Low | Depends on the workflow | Standard administration activity | One or two accounts |
| One-time-login module | High | Uses a consumable login link | Module-specific events and logs | Invitations without a shared password |
| Direct PHP script | High | Must be implemented explicitly | Custom logging | Reviewed one-off operations |
For sensitive invitations, a maintained one-time-login module can avoid sharing a password. A direct PHP script can be equally fast, but the Drush approach retains discoverable help, site aliases and repeatable option handling.
Operational checklist
Before the reset
- Run
drush @environment statusand confirm the alias, URI and database are correct. - Choose exact UIDs or one role, run
--dry-runand compare the result with the approved roster. - Confirm a database backup and restore procedure, including who can authorise access during an incident.
- Record the planned time in UTC and AEST/AEDT, then coordinate it with staff in each Australian operating region.
During and after the reset
- Supply the temporary password through the approved secret mechanism rather than an argument or literal shell command.
- Verify the forced password change and confirm that accounts outside the selector remain unaffected.
- Record the authorised operator, selected UIDs, account count and completion timestamp without retaining the temporary password.
- Clear the environment variable and monitor authentication logs for unexpected sign-ins or repeated failures.