1

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+'`
Drise
  • 4,310
  • 5
  • 41
  • 66
  • Your code looks correct, my assumption is that your `Select-String` is never matching because you need to update your `OutputEncoding` before running `wsl`: `[Console]::OutputEncoding = [System.Text.Encoding]::Unicode` – Santiago Squarzon Feb 13 '23 at 21:10
  • I got an odd output from the `echo`: `detaching System.Collections.Hashtable[0]` rather than what I expected to be `7-3` – Drise Feb 13 '23 at 21:14
  • 2
    yea, for that you need `$( )` to expand the sub expression in the string: `"attaching $($Matches[0])"` – Santiago Squarzon Feb 13 '23 at 21:15
  • @SantiagoSquarzon That did the trick. I didn't realize it was working because I didn't realize I tested "detach" and didn't understand why I saw no results. Thanks! – Drise Feb 13 '23 at 21:16
  • 1
    Closing this as duplicate since it has already been answered before and the issue seems to be fixed. @ me again in case you need this re-opened. – Santiago Squarzon Feb 13 '23 at 21:20

0 Answers0