@echo off
setlocal enabledelayedexpansion
::~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
: Detect removable drives using DiskPart...
set "diskcnt=0"
for /f "tokens=1-2 delims= " %%A in (
'^(echo list disk^)^|diskpart^|findstr /ic:"Online"'
) do (
for /f "tokens=1-3 delims= " %%X in (
'^(echo select disk %%B^&echo detail disk^)^|diskpart^|findstr /ic:"Removable"'
) do (
set /a diskcnt+=1
set "vol!diskcnt!=%%B_%%Z:"
)
)
::~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:: After detecting drives, print a menu...
echo.The script detected %diskcnt% removable drive/s:
echo.
if %diskcnt% equ 0 echo No drives found.
for /l %%X in (1,1,%diskcnt%) do (
echo. %%X. Drive !vol%%X:~2,2!
)
echo.
:choice_loop
set /p "choice=Choose a Number: "
if !choice! geq 1 if !choice! leq %diskcnt% goto :doIt
goto choice_loop
::~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:: Get and set the setting...
:doIt
echo.
set "disknum=!vol%choice%:~0,1!"
for /f "tokens=1-2 delims=:" %%F in (
'^(echo select disk %disknum%^&echo attribute disk^)^|diskpart^|findstr /bic:"Read-Only"'
) do (
set "ro_state=%%G"&set "ro_state=!ro_state: =!"
)
if /i "%ro_state%" equ "No" (
(echo select disk %disknum%&echo attribute disk set readonly)|diskpart >nul
echo Drive !vol%choice%:~2,2! is now read-only from being read/write.
) else (
(echo select disk %disknum%&echo attribute disk clear readonly)|diskpart >nul
echo Drive !vol%choice%:~2,2! is now read/write from being read-only.
)
endlocal
pause