批处理:修改COM端口号,修改串口号

今天碰到一个问题,需要把USB com port号做修改,用装置管理员轻松能实现,但是使用程式去实现时发现很麻烦。终于在网上找了个使用批次档实现的例子,真是太强大了。速度分享作为csdn处女作。

 

 

发现万能的WMI居然没有实现修改COM端口号的方法,不过用来遍历端口信息还是可以的,参考http://msdn.microsoft.com/en-us/library/aa394413(v=vs.85).aspx。 没有办法只能通过修改注册表的方式来实现,下面献上代码,自己看吧,里面有用到的2个utilities都是微软的工具:

 

COMPortNumberChanger.bat:

 

setlocal EnableDelayedExpansion
@echo off
set oldCOMPort=%~1
set newCOMPort=%~2
:ReadDeviceId
for /f %%a in ('.\tools\devcon findall =port * ^| find /i "%oldCOMPort%"') do set DEVICEID=%%a
if "%DEVICEID%" == "" (
echo Error: Cannot find device id for %oldCOMPort%, please check if device is installed correctly and try again.
echo Press any key to detect again.
pause
goto ReadDeviceId
)

:ReadFriendlyName
for /f "skip=4 tokens=1,2,*" %%a in ('reg query "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Enum\%DEVICEID%" /v FriendlyName') do set oldFriendlyName="%%c"
if %oldFriendlyName%=="" (
echo Error: Cannot find friendly name for %oldCOMPort%, check regedit: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Enum\%DEVICEID%. Check if device is installed correctly and try again.
echo Press any key to detect again.
pause
goto ReadFriendlyName
)

:FindDeviceMap
for /f "skip=4 tokens=1,2,3" %%a in ('reg query "HKLM\HARDWARE\DEVICEMAP\SERIALCOMM" /s') do (
if /i "%oldCOMPort%" == "%%c" (
set SerialCommKey="%%a"
)
)

if %SerialCommKey%=="" (
echo Error: cannot find Device map for %oldCOMPort%, check regedit: HKLM\HARDWARE\DEVICEMAP\SERIALCOMM. Check if device is installed correctly and try again.
echo Press any key to detect again.
pause
goto FindDeviceMap
)

devcon disable @"%DEVICEID%"

subinacl /keyreg "HKEY_LOCAL_MACHINE\System\CurrentControlSet\ENUM\%DEVICEID%" /grant=administrators=f
subinacl /keyreg "HKEY_LOCAL_MACHINE\System\CurrentControlSet\ENUM\%DEVICEID%\Device Parameters" /grant=administrators=f

REG ADD "HKLM\SYSTEM\CurrentControlSet\ENUM\%DEVICEID%\DEVICE Parameters" /v PORTNAME /t REG_SZ /d %newCOMPort% /F

set newFriendlyName=!oldFriendlyName:%oldCOMPort%=%newCOMPort%!

REG ADD "HKLM\SYSTEM\CurrentControlSet\ENUM\%DEVICEID%" /v FriendlyName /t REG_SZ /d %newFriendlyName% /F

REG ADD "HKLM\HARDWARE\DEVICEMAP\SERIALCOMM" /v %SerialCommKey% /t REG_SZ /d %newCOMPort% /F

REG ADD "HKLM\SYSTEM\CurrentControlSet\Control\COM Name Arbiter" /v "ComDB" /t REG_BINARY /d 0%newComPort:~3,1%00000000000000000000000000000000000000000000000000000000000000 /f

devcon enable @"%DEVICEID%"

 

调用方法:

COMPortNumberChanger.bat COM3 COM5

 

共修改了4处注册表项。 Devcon是微软提供的设备管理工具,下载地址:http://support.microsoft.com/kb/311272 ,subinacl是一款访问权限控制工具,下载地址:http://www.microsoft.com/downloads/en/details.aspx?familyid=e8ba3e56-d8fe-4a91-93cf-ed6985e3927b&displaylang=en

 

参考:

http://communities.intel.com/message/11471

 

Binhua Liu原创,转载请注明!

    原文作者:gemmo
    原文地址: https://blog.csdn.net/gemmo/article/details/6736651
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞