You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Windows 10下检测并重新分配USB驱动器盘符的脚本需求

解决Windows 10 USB盘符互换的Batch脚本方案

完整脚本

@echo off
setlocal enabledelayedexpansion

:: 定义预期的盘符映射:标签=目标盘符
set "expected_keedrive=J:"
set "expected_secondary=V:"

:: 用PowerShell导出目标USB设备的结构化信息为CSV,避免表格格式的解析问题
powershell -Command "Get-CimInstance -ClassName CIM_StorageVolume | Where-Object { $_.Label -in ('keedrive','secondary') } | Select-Object DeviceID,DriveLetter,Label | ConvertTo-Csv -NoTypeInformation" > temp_drives.csv

:: 初始化需要调整的设备信息
set "adjust_keedrive="
set "adjust_secondary="

:: 读取CSV内容,跳过表头行
for /f "skip=1 tokens=1-3 delims=," %%a in (temp_drives.csv) do (
    :: 去除CSV字段的引号
    set "deviceid=%%~a"
    set "driveletter=%%~b"
    set "label=%%~c"

    :: 对比当前盘符与预期配置
    if "!label!"=="keedrive" (
        if not "!driveletter!"=="%expected_keedrive%" (
            set "adjust_keedrive=!deviceid!|%expected_keedrive%"
        )
    ) else if "!label!"=="secondary" (
        if not "!driveletter!"=="%expected_secondary%" (
            set "adjust_secondary=!deviceid!|%expected_secondary%"
        )
    )
)

:: 生成diskpart脚本并执行盘符调整
if defined adjust_keedrive or defined adjust_secondary (
    echo select volume > adjust_drives.txt
    if defined adjust_keedrive (
        for /f "tokens=1,2 delims=|" %%x in ("!adjust_keedrive!") do (
            echo select volume %%x >> adjust_drives.txt
            echo remove letter=%%y >> adjust_drives.txt
            echo assign letter=%%y >> adjust_drives.txt
        )
    )
    if defined adjust_secondary (
        for /f "tokens=1,2 delims=|" %%x in ("!adjust_secondary!") do (
            echo select volume %%x >> adjust_drives.txt
            echo remove letter=%%y >> adjust_drives.txt
            echo assign letter=%%y >> adjust_drives.txt
        )
    )
    :: 执行diskpart命令调整盘符
    diskpart /s adjust_drives.txt
)

:: 清理临时文件
del temp_drives.csv adjust_drives.txt >nul 2>&1

echo 盘符检测与调整完成
endlocal

关键步骤说明

  1. PowerShell输出优化
    放弃Format-Table改用ConvertTo-Csv输出结构化数据,Batch可通过逗号分割轻松提取DeviceID、DriveLetter和Label,避免表格格式的解析混乱。核心PowerShell命令:

    Get-CimInstance -ClassName CIM_StorageVolume | Where-Object { $_.Label -in ('keedrive','secondary') } | Select-Object DeviceID,DriveLetter,Label | ConvertTo-Csv -NoTypeInformation
    
  2. 盘符匹配检测
    通过for /f遍历CSV内容,跳过表头后提取每个设备的标签与当前盘符,和预设的预期盘符对比,记录需要调整的设备DeviceID与目标盘符。

  3. diskpart自动化调整
    生成临时diskpart脚本,包含选择目标卷、移除当前占用盘符、分配预期盘符的命令,通过diskpart /s执行脚本完成调整。注意:脚本需以管理员身份运行,否则无权限修改盘符。

注意事项

  • 确保两个USB设备的标签keedrive和secondary唯一,避免误识别其他设备。
  • 运行前关闭所有占用这两个盘符的程序,否则diskpart无法移除盘符。

内容的提问来源于stack exchange,提问作者MoLtalbany

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 12:25:23