快速将串口添加到WSL
发布时间:2026/8/25 20:44:00 作者:尧图编辑部 阅读量:1,286

在WSL中添加USB串口设备完整指南1. 创建PowerShell脚本2. 脚本功能详解3. 运行要求与注意事项运行要求4. .ps1 脚本右键没有以管理员身份运行选项解决方法1. 创建PowerShell脚本创建一个名为添加串口到WSL.ps1的脚本文件并添加以下代码#Requires -RunAsAdministrator# Check admin rightsif(-NOT([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]Administrator)){Write-HostPlease run as Administrator!-ForegroundColorRedexit1}# Get USB device list$outputusbipd list2$nullif(-not$output){Write-Hostusbipd not found. Please install usbipd-win.-ForegroundColorRedexit1}# Parse devices (all)$devices()$lines$output-splitrn|Where-Object{$_-match^\s*\d-\d}foreach($linein$lines){$parts$line-split\s,2if($parts.Count-ge2){$busid$parts[0].Trim()$desc$parts[1].Trim()$devices[PSCustomObject]{BusID$busid;Description$desc}}}if($devices.Count-eq0){Write-HostNo USB devices found.-ForegroundColorYellowexit0}# GUI selection - show all devices without filtering$selected$devices|Out-GridView-TitleSelect USB device to attach to WSL (all devices)-OutputModeSingleif(-not$selected){Write-HostNo device selected. Exiting.-ForegroundColorYellowexit0}$busId$selected.BusID Write-HostSelected BusID:$busId($($selected.Description))-ForegroundColorGreen# BindWrite-HostBinding device$busId...-ForegroundColorCyan usbipdbind--busid$busIdif($LASTEXITCODE-ne0){Write-HostBind may already exist. Continue to attach...-ForegroundColorYellow}# AttachWrite-HostAttaching device to WSL ...-ForegroundColorCyan usbipd attach--wsl--busid$busIdif($LASTEXITCODE-eq0){Write-HostDevice attached successfully!-ForegroundColorGreen}else{Write-HostAttach failed. Please check if WSL is running.-ForegroundColorRed}2. 脚本功能详解上述脚本的主要功能包括权限检查确保脚本以管理员身份运行设备检测使用usbipd列出所有USB设备串口设备筛选自动筛选串口设备Serial/COM端口图形化选择使用Out-GridView让用户选择要连接的设备设备绑定与连接将选中的USB设备绑定并连接到WSL3. 运行要求与注意事项运行要求管理员权限usbipd命令必须使用管理员身份运行4. .ps1 脚本右键没有以管理员身份运行选项解决方法创建Add_RunAs_Admin.reg,添加下面代码,执行即可Windows Registry Editor Version5.00[HKEY_CLASSES_ROOT\SystemFileAssociations\.ps1\Shell\runas]HasLUAShield[HKEY_CLASSES_ROOT\SystemFileAssociations\.ps1\Shell\runas\command]powershell.exe\-Command\\if((Get-ExecutionPolicy ) -ne AllSigned) { Set-ExecutionPolicy -Scope Process Bypass }; %1\Add_RunAs_Admin.reg作用,它让你能像运行 .exe 程序一样右键点击 .ps1 脚本并选择“以管理员身份运行”同时自动免去了“因系统禁止脚本运行而报错”的烦恼。