@echo off
set T=c:\TEMP
set DPARTSCRIPT=%T%\diskpart.txt

rem set name for media ...
for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a"
set "YY=%dt:~2,2%" & set "MM=%dt:~4,2%" & set "DD=%dt:~6,2%"
set OSLABEL=W10-%YY%%MM%%DD%

rem create temp directory ...
mkdir %T% 1>nul 2>nul

echo ====================
echo Format Media ...
echo ====================
echo.

echo Showing disk list ...
> %DPARTSCRIPT% (
    @echo.list disk
    @echo.exit
    @echo.
)
diskpart /s %DPARTSCRIPT% 2>nul

set DISK=
:askdisk
  set /p DISK="Please select a disk: "

  > %DPARTSCRIPT% (
      @echo.select disk %DISK%
      @echo.exit
      @echo.
  )

  diskpart /s %DPARTSCRIPT% 1>nul 2>nul
  if %ERRORLEVEL% EQU 0 (
    echo OK using disk %DISK%
    GOTO CONT1
  ) else (
    echo ERROR: please select a valid disk number!
  )

  goto askdisk
:CONT1

echo.
echo IMPORTANT: USE === fat32 === for UEFI systems!
echo WARNING:   DO NOT(!) USE [ exfat ] for UEFI boot!
echo.

set FS=fat32
:askfs
  echo.
  set /p FS="Please select filesystem (fat32 or exfat) [fat32]: "
  if /i "%FS%" EQU "fat32" (
    echo IMPORTANT: maximum partition size for FAT32 is 32768!
    echo            maximum filesize for FAT32 is 4GB!
    GOTO CONT2
  )
  if /i "%FS%" EQU "exfat" (
    echo IMPORTANT: some old BIOS versions can't use exfat!
    echo WARNING:   UEFI BIOS can't use exfat for booting!
    GOTO CONT2
  )
  if /i "%FS%" EQU "" (
    GOTO CONT2
  )
  echo Please enter "exfat" or "fat32".
  goto askfs

:CONT2
echo selected: %FS%

set SIZE=32768
:asksize
  echo.
  set /p SIZE="Please enter size in MB [%SIZE%]: "

  if /i "%SIZE%" EQU "" (
    GOTO CONT3
  )

  echo %SIZE%| findstr /r "^[1-9][0-9]*$">nul
  if %errorlevel% neq 0 (
    echo Please enter an integer number!
    goto asksize
  ) else (
    echo selected size = %SIZE% [MB]
    set SIZE=size=%SIZE%
  )

:CONT3

echo.
set LABEL=%OSLABEL%
set /p LABEL="Please enter a label for the new disk [%LABEL%] : "

echo WARNING ! This will DELETE ALL data on disk number [%DISK%]
echo.
set answer=
:askyes
  set /p answer="REALLY delete disk %DISK% (Y/N)? "
  if /i "%answer:~,1%" EQU "Y" (
    GOTO CONT3
  )
  if /i "%answer:~,1%" EQU "N" (
    echo ABORT.
    del /F %DPARTSCRIPT% 1>nul 2>nul
    exit /b
  )
  echo Please type Y or N.
  goto askyes
:CONT3

rem =====
rem MAIN
rem =====

> %DPARTSCRIPT% (
  @echo.select disk %DISK%
  @echo.clean
  @echo.convert MBR
  @echo.create partition primary %SIZE%
  @echo.select partition 1
  @echo.format fs="%FS%" LABEL="%LABEL%" quick
  @echo.active
  @echo.assign
  @echo.exit
  @echo.
)

diskpart /s %DPARTSCRIPT%
if %ERRORLEVEL% NEQ 0 (
  echo ERROR: while formatting the disk!
  del /F %DPARTSCRIPT% 1>nul 2>nul
  exit /b
)
echo Media formatted.

rem cleanup ...
del /F %DPARTSCRIPT% 1>nul 2>nul

echo.
echo ======
echo READY.
echo ======

