Home > Enterprise >  Failing to match string with disk serial in batch
Failing to match string with disk serial in batch

Time:04-04

I've very little experience with batch, and right now I'm having a hard time comparing strings.

Essentially, what I actually want is to check if I have an external drive mounted and if I do trigger a command. I get all the drives serials and check if the one I'm expected is in the list:

:: I've tested with and without the EnableDelayedExpansion:
::setlocal EnableDelayedExpansion  
::setlocal EnableExtensions EnableDelayedExpansion

set torun=wmic diskdrive get serialnumber /format:value
for /f "tokens=2 delims==" %%a in ('%torun%') do (
    ::set "serial=%%a"
    echo %%a
    set "expected=     ABCDEFG1"
    if "!expected!" == "%%a" echo Valid serial number!
)

When I run this, I actually see the drivers serials printed, and the one I want is in the list, but the if statement never triggers and I actually tried several different ways. I've tried:

if %%a == "     ABCDEFG1" echo Valid serial number!
if "%%a" == "     ABCDEFG1" echo Valid serial number!
if /I "!expected!" == "%%a" echo Valid serial number!
if !expected!" == "%%a" echo Valid serial number!
if %expected% == "%%a" echo Valid serial number!
if "%expected%" == "%%a" echo Valid serial number!

And several other variations, sometimes the script run but doesn't trigger the echo Valid serial number!, and othertimes I get echo was unexpected at this time.

It's worth noting that in the echo %%a some drivers come with several trailing spaces before the serial, and I've tried checking with both the spaces and without.

PS.: I've the correct serial in my script.

CodePudding user response:

I would do it differently:

@%SystemRoot%\System32\wbem\WMIC.exe DiskDrive Where "SerialNumber Like '            
  • Related