如何修改Windows批处理脚本为所有检测到的硬盘追加显示设备名称
批处理脚本修改方案
实现逻辑
通过WMI关联类建立「盘符→磁盘分区→物理磁盘」的映射关系,提前将所有盘符对应的硬盘设备名存入变量缓存,输出时直接调用即可匹配到对应名称。
完整修改后脚本
@echo off setlocal enabledelayedexpansion call :setESC call :hdd-info endlocal echo. 按任意键退出 &>&nul timeout /t -1 &exit /B REM - 配置ANSI转义字符 ------------------------------------------------ :setESC for /F "tokens=1,2 delims=#" %%a in ('"prompt #$H#$E# & echo on & for %%b in (1) do rem"') do ( set ESC=%%b exit /B 0 ) REM ------------------------------------------------------------------------------ :: - 获取存储/硬盘信息 ------------------------------------------------------ :hdd-info :: 启用Unicode符号支持 chcp 65001 >nul set "GB=1073741824" :: 预生成盘符→物理磁盘设备名的映射缓存 for /f "skip=2 tokens=2,3 delims=," %%a in ( '%SystemRoot%\System32\wbem\wmic.exe path Win32_LogicalDiskToPartition get Antecedent^,Dependent /format:csv 2^>nul' ) do ( for /f "tokens=2 delims==" %%d in ("%%a") do set "partition=%%d" for /f "tokens=2 delims==" %%l in ("%%b") do set "drive_letter=%%l" for /f "skip=2 tokens=2 delims=," %%c in ( '%SystemRoot%\System32\wbem\wmic.exe path Win32_DiskDriveToDiskPartition where "Antecedent like '%%!partition!'" get Dependent /format:csv 2^>nul' ) do ( for /f "tokens=2 delims==" %%e in ("%%c") do set "disk=%%e" for /f "skip=2 tokens=2 delims=," %%f in ( '%SystemRoot%\System32\wbem\wmic.exe path Win32_DiskDrive where "DeviceID='!disk!'" get Caption /format:csv 2^>nul' ) do set "disk_name_!drive_letter:~0,2!=%%f" ) ) for /f "skip=1 delims=" %%i in ('%SystemRoot%\System32\wbem\wmic.exe logicaldisk get deviceid^,freespace^,size^') do (for /f "tokens=1-3" %%j in ("%%i") do call :output %%j %%k %%l) :: 关闭Unicode符号支持 chcp 1252 >nul goto :eof :output if "%3"=="" ( :: echo. Volume %optical_drive_letter%\ - %optical_drive_type% ^(%optical_drive_name%^) goto :eof ) :: 处理无匹配设备名的情况 if "!disk_name_%1!"=="" set "disk_name_%1=未知存储设备" for /f "tokens=1-4" %%i in ( 'mshta vbscript:Execute("CreateObject(""Scripting.FileSystemObject"").GetStandardStream(1).Write(FormatNumber(%3/%GB%, 2) & "" "" & FormatNumber((%3-%2)/%GB%, 2) & "" "" & FormatNumber(%2/%GB%, 2) & "" "" & Round((%3-%2)*50/%3)):Close"^)' ) do ( set "size=%%i" set "used=%%j" set "free=%%k" set /a "nUsed=%%l, nFree=50-%%l" ) echo( Volume %1\ !disk_name_%1! echo( 总容量 : %size:~-10%GB echo( 已用空间 : %used:~-10%GB echo( 可用空间 : %free:~-10%GB for /l %%i in (1 1 %nUsed%) do <nul set /p "=%ESC%[91m▓%ESC%[30m" for /l %%i in (1 1 %nFree%) do <nul set /p "=%ESC%[92m▓%ESC%[30m" echo( &echo( goto :eof :: ------------------------------------------------------------------------------
注意事项
- 脚本默认适配Windows 10 1511及以上版本系统,旧版本系统需提前开启终端ANSI转义符支持
- 部分受限权限环境可能需要以管理员身份运行脚本,才能正常读取物理磁盘设备信息
内容的提问来源于stack exchange,提问作者Bri
相关产品推荐
相关产品推荐

