使用DISKPART删除驱动器号的BAT/CMD文件

问题描述:

我正在尝试编写一个批处理文件来删除分配给没有文件系统的分区的驱动器号。我无法使用wmi,因为它在WinPE恢复环境中使用。使用DISKPART删除驱动器号的BAT/CMD文件

DISKPART> list volume 

    Volume ### Ltr Label   Fs    Type   Size  Status  Info 
    ---------- --- ----------- -----  ----------  ------- --------- -------- 
    Volume 0  K        DVD-ROM   0 B No Media 
    Volume 1  L        DVD-ROM   0 B No Media 
    Volume 2  C Windows 7 NTFS  Partition  80 GB Healthy  System 
    Volume 3  D       Partition  500 GB Healthy  System 
    Volume 4         Partition  500 GB Healthy  System 
    Volume 5  E       Partition  500 GB Healthy  System 

DISKPART> exit 

For loop = 0 to 5 
If Type[loop]="Partition" then 
    If Ltr[loop]<>"" then 
     If Fs[loop]="" then 
      SELECT VOLUME loop 
      REMOVE LETTER Ltr[loop] 
     End If 
    End If 
End If 
Next 

这是我迄今为止...

@echo off 

For /F "Tokens=1,2,3,4,5,6*" %%I In ('echo.list volume^|diskpart.exe^|findstr /I /R /C:"Volume [0-9]"') Do (
echo %%I %%J %%K %%L %%M %%N 
if "%%N"=="Partition" (
if NOT "%%K"=="" (
if "%%M"=="" (
echo mountvol %%K: /D 
) 
) 
) 
) 

上述不起作用,因为输出是分隔空间和一些空白列搞乱了解析。

的另一种尝试,我想这样的作品,但它可能是更好的

@echo off 
cd /d "%~dp0" 
for /f "skip=8 tokens=*" %%A in ('echo.list volume && echo.exit^|%windir%\system32\diskpart.exe') do (
echo.%%A ^^| find /I "  Partition" >nul && (
for /f "tokens=3 delims= " %%B in ("%%A") do (echo.mountvol %%B: /D) 
) 
) 
pause 
exit 

你知道为什么上面需要2 ^前| (管)?上述

@echo off 
for /f "skip=9 tokens=*" %%A in ('echo.list volume^| diskpart') do (
echo."%%A"| find /I "  Partition" >nul && (
for /f "tokens=3 delims= " %%B in ("%%A") do (echo.mountvol %%B: /D & mountvol %%B: /D) 
) 
) 
pause 
exit 

似乎是现在的工作,我不得不把周围的回声双引号。“%% A”,然后我管之前取出的2 ^。

@echo off 
setlocal enableDelayedExpansion 
set "validDrives=;C;D;E;F;G;H;I;J;K;L;M;N;O;P;Q;R;S;T;U;V;W;X;Y;Z;" 
for /f "skip=9 tokens=*" %%A in ('echo.list volume^| diskpart') do (
echo."%%A"| find /I "  Partition" >nul && (
for /f "tokens=3 delims= " %%B in ("%%A") do (
if "!validDrives:;%%~B;=!" neq "!validDrives!" (echo.mountvol %%B: /D & mountvol %%B: /D) 
) 
) 
) 
pause 
exit 

以上是我的工作脚本,我添加了一些代码来验证驱动器号。

如果有人可以提供有关如何改善这个问题的建议,那么请做!

谢谢

+0

他从来没有说过。他遵循堆栈溢出的规则。 – Jahwi

+0

您是否使用NTFS以外的其他文件系统?如果只使用NTFS,它将简化脚本。 – foxidrive

我可能有一个更简单的解决方案给你。只要抓住了整条生产线,并使用批处理子串拉出右件

@echo off 
setlocal ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION 
    for /f "delims=" %%i in ('^ 
     echo list volume ^|^ 
     diskpart ^|^ 
     findstr Volume ^|^ 
     findstr /v^
     /c:"Volume ### Ltr Label  Fs  Type  Size  Status  Info"^ 
     ') do (
     set "line=%%i" 
     set letter=!line:~15,1! 
     set fs=!line:~32,7! 
     if not "  "=="!fs!" (
      if not " "=="!letter!" (
       call :removeVol !letter! 
      ) 
     ) 
    ) 
endlocal 
exit /b 

:removeVol 
    (
     echo select volume %1 
     echo remove letter %1 
    ) | diskpart 
exit /b 

卷上市的for语句产生不列标题或分隔符。

do语句执行子字符串操作。

确保您具有diskpart命令的管理员权限。我对你的WinRE环境有点好奇。我工作的大多数人都有一个最小的WMI实例运行,以及WSH,这将使这个代码更清洁。