diskpart is terminal application which means it has it's own CLI (command line interface). That means, that if you want to write a command to the diskpart, you have to write it to the diskpart's own CLI as a stdin (standard input). This is the reason, why you cannot wirte your commands via batch file, because your diskpart commands are run as next commands for cmd.exe after diskpart exits.
Now we only must "lie" to diskpart and emulate stdin to his CLI.
We can achieve it like this:
(echo Rescan
echo List Disk
echo Select Disk 3
echo List Partition
echo Select Partition 3
echo Delete Partition Override
) | diskpart
pause
So, this code above does the following:
-
The echo commands will generate stdout (standard output). Usually our command-line interpreter, cmd.exe would just print out this stdout on the screen. (You can try that by running only the echo commands with parenthesis in cmd.exe)
-
Then, using the pipe
|
we redirect stdout of those echo commands into the diskpart application. So the stdout from echo's will now act as stdin for the diskpart application.
So, you run diskpart, diskpart gets input from echo's, similiarly as it would get input from keyboard, and of course it works!
That is all, simple and easy solution!
another method for you to perform your diskpart script
Place your diskpart commands (the ones you type after typing diskpart
) in a text file like script.txt
and call diskpart with the following command.
@echo off
diskpart /s script.txt
But be very careful that your commands are correct and well tested and don't call the batch file diskpart.
See here for more information: DiskPart Command-Line Options | Microsoft Learn
you also can do this even easier in PowerShell by using a here-string
((@"
Rescan
List Disk
Select Disk 3
List Partition
Select Partition 3
Delete Partition Override
"@
)|diskpart)
If you needed that to be in a batch file, you could always inject it directly with one of the tricks you can find in other StackOverflow posts, as well as this thread.
e.g.
<# :
@PowerShell -NoLogo -NoProfile -Command Invoke-Expression $('$args=@(^&{$args} ($input^|?{$_}));'+(${%~f0}^|Out-String)) & @GOTO :EOF
#>
((@"
Rescan
List Disk
Select Disk 3
List Partition
Select Partition 3
Delete Partition Override
"@
)|diskpart)