It looks to me like this will need two different approachs:
- First we need to handle the case when WSL starts up while the drive is already attached.
- And we also need to handle the case when the drive is attached while WSL is already running.
Drive already attached when WSL starts
The first part should be pretty easy.
I don't want to put this command in a .bashrc type of file because having to type in my password every time I open a terminal
That's simple to overcome. Add the following to your ~/.bashrc
instead:
wsl.exe -u root -e mount -t drvfs D: /mnt/d > /dev/null 2>&1
That will mount the drive if it's available. If not, it will silently fail.
Drive is attached while WSL is running
It's not easy, and it probably needs more error handling to be "robust", but I was able to get this to work by creating a PowerShell script to:
- Register an action when a USB drive is attached
- Run
wsl -u root -e mount -t drvfs /mnt/<driveletter> <Drive>
when the event fires.
$query = "select * from __InstanceCreationEvent within 5 where TargetInstance ISA 'Win32_LogicalDisk' and TargetInstance.DriveType = 2"
$action = {
$drivePath = $event.SourceEventArgs.NewEvent.TargetInstance.Name
$driveLetter = $drivePath.ToLower()[0]
wsl -u root -e mount -t drvfs $drivePath /mnt/$driveLetter
}
Register-WmiEvent -Query $Query -Action $Action -SourceIdentifier USBFlashDriveWSLMount
Note that this needs to run in Windows PowerShell (rather than PowerShell Core) since it uses WMIEvent
. I'm sure there's a PowerShell Core equivalent using CIM, but I haven't tried it that way yet.
If you run into a problem, check the output. From PowerShell:
Get-Job
# Get the Id of the job then
Receive-Job <job_id>
In theory, you can set this script to run at Windows Login via Task Scheduler, but I haven't tried it. I'm 80% confident it will work. You'll need to call it through the powershell
command (not pwsh
since it uses WMIEvent).
Note, there's also apparently a way to register the event listener permanently though CIM. I spent some time on this last week, but got rabbit-trailed when I followed some documentation that created a CIM class on my system that I couldn't get rid of. I may come back to it eventually, but hopefully this works for you as a Scheduled Task. I just didn't want to hold off posting until I got it "just right", because I might never finish it up.