How to Automate Windows Diskpart Commands in a Script

Being able to automate disk partitioning, volume creation, and filesystem formatting can be very useful. It is especially handy for imaging processes, e.g. from a WinPE boot disk.

The windows diskpart command can be automated using a simple text file. Unfamiliar with Diskpart? Open Windows Command Processor (cmd.exe) and type:

diskpart

help

If you want help with a specific command, type:

help <command>

Where <command> is the command that you want help with.

To automate diskpart, you simply need to create a text file with your diskpart commands, then call diskpart from your command prompt or script and pass it the name of the text file.

For example, let’s say that you have booted a computer to WinPE, and wish to wipe the local “C:” drive and create a fresh one. To do so, open notepad.exe, then type the following:

select disk 0

clean

create partition primary

assign letter=C

active

format fs=ntfs label=Windows quick

Now save that as WipeC.txt and close Notepad.

Then run it like so:

diskpart.exe /s WipeC.txt

Please note that this example will completely remove the contents of the local Disk 0!

More specifically, it will: wipe all partitions off of Disk 0, create a single primary partition which will occupy the whole disk, assign that partition the drive letter C:, set it as active so that you can boot from it, and then create a volume called “Windows” formatted quickly as NTFS.

The Conversation

Follow the reactions below and share your own thoughts.

  • http://blogs.tech-recipes.com/jimmyselix jimmyselix

    Nice! Perfect for deployment and imaging solutions too!

  • NightWalkercito

    I LOVE YOU!, seriusly! A LOT OF THX!

  • jani

    Tanks for this

  • Kris

    I tried to run the script above and all it did was list the help options. At the prompt I typed diskpart /s f:\script\script.txt and pressed enter. Once I hit enter listed was a list of the help options. Can you please let me know what I did wrong?

    • Ben

      Can you please post the contents of “f:\script\script.txt”?