@set @JScript=1/*
@echo off
setlocal EnableExtensions EnableDelayedExpansion

rem ==============================
rem print_drop.bat
rem Drag & drop one or more files onto this .bat to print their names.
rem ==============================

rem Force working directory to the folder where this script lives
cd /d "%~dp0"

if exist "%~dp0tools\dfu-util-static.exe" (
    set "DFU_UTIL=%~dp0tools\dfu-util-static.exe"
)else if exist "%~dp0dfu-util-static.exe" (
    set "DFU_UTIL=%~dp0dfu-util-static.exe"
)else (
    echo [ERROR] dfu-util-static executable not found in "%~dp0" or "%~dp0tools\" folder
    pause
    exit /b 1
)
set "DFU_NAME=QDrive DFU"

if "%~1"=="" (
  echo Usage:
  echo   1^) Drag and drop file^(s^) onto print_drop.bat
  echo   2^) Or run in cmd: print_drop.bat ^<file1^> [file2 ...]
  echo.
  echo No input files were provided.
  echo.
  pause
  exit /b 0
)

echo Arguments: %*
echo.

set "idx=0"
:loop
if "%~1"=="" goto done
set /a idx+=1

echo [%idx%] Full path : %~f1
echo [%idx%] File name : %~nx1

echo.
echo ===== Step 1/3: Detect DFU device: "%DFU_NAME%" =====

set "PNPID="

rem Query WMI using embedded JScript (No temp files, works on XP-11)
for /f "delims=" %%I in ('cscript //nologo //E:JScript "%~f0" "%DFU_NAME%"') do set "PNPID=%%I"

if not defined PNPID (
    echo [ERROR] Not found: %DFU_NAME%
    pause
    exit /b 2
)


echo [OK] Found PNPDeviceID:
rem IMPORTANT: escape '&' when echoing under delayed expansion, otherwise cmd may treat it as command separator
echo   !PNPID:^&=^^^&!

echo.
echo ===== Step 2/3: Extract VID/PID =====

set "VID="
set "PID="
for /f "tokens=2 delims=\\" %%S in ("!PNPID!") do (
    for /f "tokens=1,2 delims=&" %%A in ("%%S") do (
        for /f "tokens=2 delims=_" %%V in ("%%A") do set "VID=%%V"
        for /f "tokens=2 delims=_" %%P in ("%%B") do set "PID=%%P"
    )
)

if not defined VID (
    echo [ERROR] Failed to extract VID from PNPDeviceID
    pause
    exit /b 6
)
if not defined PID (
    echo [ERROR] Failed to extract PID from PNPDeviceID
    pause
    exit /b 7
)

echo [OK] VID:PID = !VID!:!PID!

echo.
echo ===== Step 3/3: Write and leave DFU =====

cmd /c ""%DFU_UTIL%" -s :leave -d %VID%:%PID% -D "%~f1"

@REM Uncomment to process multiple files
@REM shift
@REM goto loop

:done
endlocal

rem Keep the window open so you can see the output when launched from Explorer
pause
goto :EOF

*/
var args = WScript.Arguments;
if (args.length > 0) {
    var dfuName = args(0);
    try {
        var wmi = GetObject("winmgmts:\\\\.\\root\\cimv2");
        var items = wmi.ExecQuery("Select * from Win32_PnPEntity Where Name = '" + dfuName + "' And PNPDeviceID Like 'USB%'");
        var enumItems = new Enumerator(items);
        for (; !enumItems.atEnd(); enumItems.moveNext()) {
            var item = enumItems.item();
            WScript.Echo(item.PNPDeviceID);
            break;
        }
    } catch(e) {}
}
