WindowsServer

Powershell – How to format all disks

Did you know that you can manage disks, partitions and volumes using Powershell? Microsoft released a lot of cmdlet in order to facilitate handling of disks.

With virtualization, you can easily add disk to your server, but you have to create the volume yourself. I wrote a script that you can integrate in your process, runbooks or others.

Disks initialization

First thing to do, is to prepare disks to host volume. We need to set disks online and to disable Read only.

try {
#Set all disks, except the first disk, to online and writable
Get-Disk | ?{$_.number -ne 0}| Set-Disk -IsOffline $False
Get-Disk | ?{$_.number -ne 0}| Set-Disk -isReadOnly $False
 
#Initialize all disks
Get-Disk | ?{$_.number -ne 0}| Initialize-Disk -PartitionStyle GPT
}catch{
Write-Host $_.Exception.Message
}

Volume

Once disks are ready, we need to create, and format volume.

try {
#Create Partition on all disk, auto assign letter and use maximum size
Get-Disk | ?{$_.number -ne 0}| New-Partition -AssignDriveLetter -UseMaximumSize
#Get all partitions and format them
Get-Disk | ?{$_.number -ne 0}| Get-Partition |?{$_.type -like "Basic"}| Format-Volume -Confirm:$false
}catch{
Write-Host $_.Exception.Message
}

Remote

If you want to execute these command on a remote host, it is possible. We will use the cmdlet Invoke-Command

try {
#Set all disks, except the first disk, to online and writable
Invoke-Command -ComputerName $lServerName -ScriptBlock {Get-Disk | ?{$_.number -ne 0}| Set-Disk -IsOffline $False}
Invoke-Command -ComputerName $lServerName -ScriptBlock {Get-Disk | ?{$_.number -ne 0}| Set-Disk -isReadOnly $False}
#Initialize all disks
Invoke-Command -ComputerName $lServerName -ScriptBlock {Get-Disk | ?{$_.number -ne 0}| Initialize-Disk -PartitionStyle GPT}
#Create Partition on all disk, auto assign letter and use maximum size
Invoke-Command -ComputerName $lServerName -ScriptBlock {Get-Disk | ?{$_.number -ne 0}| New-Partition -AssignDriveLetter -UseMaximumSize}
#Get all partitions and format them
Invoke-Command -ComputerName $lServerName -ScriptBlock {Get-Disk | ?{$_.number -ne 0}| Get-Partition |?{$_.type -like "Basic"}| Format-Volume -Confirm:$false }			
}catch{
Write-Host  $_.Exception.Message
}

More

You can get more information about Disk Management cmdlet here.

Share