Context: USBIPD allows attaching and detaching a microSD card to a WSL instance. This usually involves listing all devices then manually selecting the appropriate bus ID to perform on. Typical output of usbipd wsl list
:
BUSID VID:PID DEVICE STATE
1-7 04f2:b5e7 HP HD Camera, HP IR Camera Not attached
7-3 2537:1081 USB Mass Storage Device Not attached
8-5 2109:8884 USB Billboard Device Not attached
I want to be able to automate attaching (usbipd wsl attach --busid <bus ID>
) and detaching (usbipd wsl detach --busid <bus ID>
) using Powershell aliases. The bus ID can change pretty frequently, so this must be handled by some sort of Regex I figure.
I would make heavy use of grep
in a Linux environment to do this, but I'm struggling to do this correctly in PS. This is what I've tried so far and I felt it was close, but I think I'm still missing something.
Powershell profile:
Function AttachUSBDevice {
usbipd wsl list | Select-String 'USB Mass Storage Device' | ForEach-Object { if($_ -match '\d+-\d+') { usbipd wsl attach --busid $Matches[0]; ; echo "attaching $Matches[0]" }}
}
Function DetachUSBDevice {
usbipd wsl list | Select-String 'USB Mass Storage Device' | ForEach-Object { if($_ -match '\d+-\d+') { usbipd wsl detach --busid $Matches[0]; echo "detaching $Matches[0]" }}
}
Set-Alias -Name attach -Value AttachUSBDevice
Set-Alias -Name detach -Value DetachUSBDevice
How do I do this correctly in Powershell?
As an example of how grep
would handle this (not considering if there would be multiple matches found):
usbipd wsl detach --busid `usbipd wsl list | grep 'USB Mass Storage Device' | grep -o '\d+-\d+'`