0

So I have a batch file that I am trying to find the drive and partition number of the C: drive. If I comment out the encapsulating 'if', the block of code works just fine but with it, it fails. Any help would be appreciated!

@echo off
set DISK=
set PART=

if [%DISK%]==[] (
    rem Get the hard drive information by first searching for and isolating just the C: in the output
    for /f "tokens=1 delims==" %%a in ('wmic Path Win32_LogicalDiskToPartition Get Antecedent^,Dependent /Format:list ^| find /n "=" ^| find "C:"') do set BOOT=%%a
    rem remove the preceeding "[" character
    set BOOT=%BOOT:[=%
    rem remove the appended "]Dependent" string so now we have just the index value of the C:
    set BOOT=%BOOT:]Dependent=%
    rem subtract, by 1, the line indicating the C: so we can now only parse the line that preceeds it in the output to get the actual drive and partition data!
    set /a BOOT=%BOOT%-1
    rem now call the 'wmic' command again but with the prior line being stored for parsing
    for /f "tokens=3 delims==" %%a in ('wmic Path Win32_LogicalDiskToPartition Get Antecedent^,Dependent /Format:list ^| find /n "=" ^| find "[%BOOT%]"') do set DRIVE=%%a
    rem Remove all the quotes from the results
    set DRIVE=%DRIVE:"=%
    for /f "tokens=1,2 delims=," %%a in ("%DRIVE%") do (
        set DISK=%%a
        set PART=%%b
    )
    set DISK=%DISK:Disk #=%
    set PART=%PART: Partition #=%
    if [%DISK%]==[] (
        echo ERROR: You must have a disk number for C: to continue!
        goto ERR
    )
    if [%PART%]==[] (
        echo ERROR: You must have a partition number for C: to continue!
        goto ERR
    )
    echo    Obtained Drive Info: %DRIVE%
)
pause
user1646428
  • 179
  • 2
  • 12
  • Read about (code blocks) and [delayedexpansion.html](http://ss64.com/nt/delayedexpansion.html) IMO the most recurring batch question. Also I suggest to use double quotes instead of square brackets `[]` to check for empty vars (or use if defined). –  Oct 25 '18 at 19:54
  • Oh yeah, I forgot about the delayed expansion. Thanks LotPings! If you want to create an answer, I will mark it. – user1646428 Oct 25 '18 at 20:36
  • 1
    You could change the `FOR /F` commands to use additional delimiters so that you wouldn't need to use extra `SET` commands to remove the brackets and quotes. – Squashman Oct 25 '18 at 20:38

0 Answers0