获取驱动器列表后删除最后一个空条目 - 批处理脚本

Removing Last Empty Entry After Getting Drive List - Batch Script

这是我的批处理脚本,它为您提供硬盘盘符列表:

@echo off
setlocal enabledelayedexpansion
for /f "skip=1 tokens=1,2 delims=: " %%a in ('WMIC LogicalDisk Where "DriveType='3'" Get DeviceID') do (
   set "_DRIVE.LETTERS.USED=!_DRIVE.LETTERS.USED!%%a:\ ; "
)
echo %_DRIVE.LETTERS.USED%

我的预期输出是:C:\ ; D:\ 但它会打印 C:\ ; D:\ ; :\ ;

如何删除最后多余的 :\ ;

过滤相关行:... Get DeviceID^|find ":"') do ... 删除空条目,echo %_DRIVE.LETTERS.USED:~0,-3% 删除最后一个 space/semicolon/space:

@echo off
setlocal enabledelayedexpansion
for /f "skip=1 tokens=1,2 delims=: " %%a in ('WMIC LogicalDisk Where "DriveType='3'" Get DeviceID ^|find ":"') do (
   set "_DRIVE.LETTERS.USED=!_DRIVE.LETTERS.USED!%%a:\ ; "
)
echo %_DRIVE.LETTERS.USED:~0,3%

空行实际上是在使用 for /Fwmic 的 Unicode 输出转换为 ASCII/ANSI 文本。要摆脱这些东西,只需环绕另一个 for /F 循环 *:

@echo off
setlocal EnableDelayedExpansion
for /F "skip=1" %%I in ('wmic LogicalDisk where "DriveType=3" get DeviceID') do (
    for /F %%J in ("%%I") do (
        set "_DRIVE.LETTERS.USED=!_DRIVE.LETTERS.USED!%%J\ ; "
    )
)
endlocal & echo %_DRIVE.LETTERS.USED%

我还删除了选项 tokens(默认值:1)和 delims(默认值:SPACETAB) 因为这里不再真正需要它们(拆分冒号然后将其重新附加到循环体中是没有意义的)。


一个更通用的解决方案,甚至在值中有 SPACEs 时也有效,是使用 /VALUE 选项 wmic,因为 returned 值不再用尾随 SPACEs 填充,没有 /VALUE 时就是这种情况。要在更改后的输出中拆分前面的值名称(如 DeviceID=C:),请设置内部 for /F 循环的适当 tokensdelims 选项:

@echo off
setlocal EnableDelayedExpansion
for /F "delims=" %%I in ('wmic LogicalDisk where "DriveType=3" get DeviceID /VALUE') do (
    for /F "tokens=1* delims==" %%J in ("%%I") do (
        set "_DRIVE.LETTERS.USED=!_DRIVE.LETTERS.USED!%%K\ ; "
    )
)
endlocal & echo %_DRIVE.LETTERS.USED%

这会从值中删除任何前导等号,但这不会发生在手头的值上,而且这种情况通常应该极少发生。


*) 此双循环方法归功于用户 dbenham ‐ see his answer to Why is the FOR /f loop in this batch script evaluating a blank line? as well as this external article WMIC and FOR /F : A fix for the trailing <CR> problem