Automating Formatting a Disk with PowerShell

Recently I've had a request to format a drive and create multiple partitions of varying sizes. Instead of using Disk Manager or Disk Part. I wanted to go for a more automated solution using PowerShell.

The first step is to list all the available disks on the system and then store the value of the disk you would like to work with in a variable. I am using Out-Gridview with -PassThru to allow the selection of any drive currrently plugged in.

The second step will be to format or clear the drive and convert to GPT if needed.

Finally, create the partitions inputting your parameters for Size, Filesystem, and Label. Your script should look like below, adjust for size and label accordingly.

*Note: Keep in mind the partitions will be created in the same order as they are coded. If you don't use up your whole drive space with the partitions, the excess space will be Unallocated at the end of the disk.

#Here we are storing the disk object into a variable to work with it further.
$initDisk = Get-Disk | Out-GridView -PassThru
#Clean/clear the disk and convert to GPT if not done so initially
$initDisk | Clear-Disk -RemoveData
#Check to see if the disk is GPT after clearing, sometimes it is already set
if ($initDisk.PartitionStyle -eq "GPT"){
"Disk is already GPT, creating partitions..."}
Else{
#Initialize the disk
Initialize-Disk -Number $initDisk.Number -PartitionStyle GPT}
#Create Partitions and size appropriately
$initDisk | New-Partition -Size 4GB -DriveLetter D | format-volume -filesystem NTFS -newfilesystemlabel Partition1
$initDisk | New-Partition -Size 4GB -DriveLetter P | format-volume -filesystem NTFS -newfilesystemlabel Partition2
$initDisk | New-Partition -Size 4GB -DriveLetter I | format-volume -filesystem NTFS -newfilesystemlabel Partition3
$initDisk | New-Partition -Size 4GB -DriveLetter S | format-volume -filesystem NTFS -newfilesystemlabel Partition4