It's meant to be used in a custom drush command.
If you really want to set it in an event I haven't found one neither ...
But - you could hook a drush command in your own custom command.
See https://www.drush.org/latest/hooks/#core-hooks
So you could create a drush command, that does nothing but implements of a hook, for your desired one(s), fe.
<?php
namespace Drupal\my_demo\Commands;
use Drupal\Core\Session\UserSession;
use Drush\Commands\DrushCommands;
use Drupal\Core\Session\AccountSwitcherInterface;
/**
* A Drush commandfile.
*
* In addition to this file, you need a drush.services.yml
* in root of your module, and a composer.json file that provides the name
* of the services file to use.
*
* See these files for an example of injecting Drupal services:
* - http://cgit.drupalcode.org/devel/tree/src/Commands/DevelCommands.php
* - http://cgit.drupalcode.org/devel/tree/drush.services.yml
*/
class DemoCommands extends DrushCommands {
/**
* The account switcher service.
*
* @var \Drupal\Core\Session\AccountSwitcherInterface
*/
protected $accountSwitcher;
/**
* SimplesitemapCommands constructor.
*
* @param \Drupal\Core\Session\AccountSwitcherInterface $account_switcher
* The account switching service.
*/
public function __construct(AccountSwitcherInterface $account_switcher) {
$this->accountSwitcher = $account_switcher;
}
/**
* @hook script
*/
public function runEveryScriptAsUserOne(CommandData $commandData): void {
// Switch to root user (--user option was removed from drush 9).
$this->accountSwitcher->switchTo(new UserSession(['uid' => 1]));
// Switching back not possible ..
}
}
but - I would not really recommend this, as you cannot switch back, so the account switch is not targeted.
I would really suggest you implement a full custom command!