How to select a disk during an automated diskpart script?

196 Views Asked by At

I recently created a script at work to automate some processes. Nothing fancy, just partitioning and formatting a USB HDD. It works, but I would like to be somewhat safer in my implementation.

This is my script now:

@echo off
DISKPART /s C:\Format.txt

then this is what's in my txt file:

SELECT DISK 7
CLEAN
CREATE PARTITION PRIMARY SIZE=1024
SELECT PARTITION 1
ACTIVE
FORMAT FS=FAT32 LABEL="PARAGON" QUICK
ASSIGN LETTER=P
CREATE PARTITION PRIMARY SIZE=952842
SELECT PARTITION 2
ACTIVE
FORMAT FS=NTFS LABEL="Backup" QUICK
ASSIGN LETTER=Q

And it works just fine and does what it should do. My only problem is if someone doesn't check beforehand, maybe used a USB stick before connecting the USB HDD and it is no longer Disk 7.

What I would like it to do would be starting with a "list disk" command, so I can see which drive number my HDD has, then type "7" for example, hit enter and it should execute the above code with disk 7.

Is this at all possible? Thanks for your help!

Already tried googling and reading answers from similar questions, but couldn't get it to work.

1

There are 1 best solutions below

0
On

You can't "inject" something into a running diskpart, so you need two steps: one to get a list of disks, then asking the user for the desired number, then another diskpart to "do the work".

You can create the script for the second diskpart "on the fly":

@echo off
setLocal 

>list.txt echo LIST DISK
diskpart /s list.txt
set /p "userchoice=Enter disk number: "
(
echo SELECT DISK %userchoice%
echo CLEAN
echo CREATE PARTITION PRIMARY SIZE=1024
echo SELECT PARTITION 1
echo ACTIVE
echo FORMAT FS=FAT32 LABEL="PARAGON" QUICK
echo ASSIGN LETTER=P
echo CREATE PARTITION PRIMARY SIZE=952842
echo SELECT PARTITION 2
echo ACTIVE
echo FORMAT FS=NTFS LABEL="Backup" QUICK
echo ASSIGN LETTER=Q
)>format.txt
diskpart /s format.txt

(not fully tested - for obvious reasons)