I need to create a batch file which partitions and formats a USB drive. This is to create a Windows 7 USB boot disk.
DISKPART is the tool used and you pass it instructions as in:
DISKPART /s instructions.txt
In my case I want my instructions to look like this:
example prepdisk.txt
SELECT DISK <Prompt user to either enter a number or q for quit>
CLEAN
CREATE PARTITION PRIMARY
FORMAT QUICK FS=NTFS LABEL="Windows"
ACTIVE
ASSIGN LETTER="C"
Then I would have a batch file like this:
prepdisk.bat:
DISKPART /s prepdisk.txt
But I am stuck on how to prompt the user for a disk id. I also want to be able to quit if unsure because obviously formatting the wrong drive could be dangerous.
See set /?
help. You will need to use set /p var=promptText
to ask a user for input. What the user types will be stored in the indicated variable.
Diskpart
accepts commands from a script file and from stdin. So we can pipe commands to it to show information to the user and check the selection.
Use this as a base (save as a .cmd
file) and adapt to your needs.
@echo off
setlocal enableextensions disabledelayedexpansion
:ask
rem select disk to format
call :showDiskTable
set /p "diskNumber=Type number of disk to format: " || goto :processCancelled
rem test disk selection
( echo select disk %diskNumber%
echo list disk
) | diskpart | findstr /b /c:"*" >nul || (
echo(
echo WRONG SELECTION
echo(
goto :ask
)
rem confirm disk selection
cls
call :showDiskTable
set "answer=%random%%random%"
set /p "confirm=If you are sure you want to format disk %diskNumber%, type %answer%:"
if not "%confirm%"=="%answer%" goto :processCancelled
rem Create script file
set "scriptFile=%temp%\%~nx0.%random%%random%%random%.tmp"
> "%scriptFile%" (
echo SELECT DISK %diskNumber%
echo CLEAN
echo CREATE PARTITION PRIMARY
echo FORMAT QUICK FS=NTFS LABEL="Windows"
echo ACTIVE
echo ASSIGN LETTER="C"
)
rem execute script file
type "%scriptFile%"
rem diskpart /s "%scriptFile%"
rem cleanup and exit
del /q "%scriptFile%"
echo(
echo DONE
echo(
exit /b 0
:showDiskTable
echo =====================================================
echo list disk | diskpart | findstr /b /c:" "
echo =====================================================
echo(
goto :eof
:processCancelled
echo(
echo PROCESS CANCELLED
echo(
exit /b 1
Note that for testing the diskpart /s file
is disabled and the script generated is only echoed to console. When everything works as intended, remove the type
line (not needed) and the rem
before the diskpart