batch-file-for-running-diskpart

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:

  1. 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)

  2. 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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值