In this post you will learn how to perform various disk management tasks with PowerShell. I will explain how to list disks, format disks, initialize disks, and create and delete volumes and partitions.

List disks ^

Before you can begin configuring and managing your Windows Server storage, you first need to fetch the list of disks presented on the machine using PowerShell.

# List all disks
Get-Disk

# List disks that are not system disks
# to avoid accidently formatting your system drive
Get-Disk | Where-Object IsSystem -eq $False

# List disks that are offline
Get-Disk | Where-Object IsOffline –Eq $True
List disks with PowerShell

List disks with PowerShell

Format a disk ^

Having new disks present on the server is a totally different case, but there may be scenarios where you want to format existing disks and then create partitions and volumes. You can use the Clear-Disk cmdlet to remove all partition information and uninitialize it, which will erase the data on the disk.

This is an unrecoverable process, so please make sure to back up your disk before running the command.

# Clear a blank disk with the disk number
Clear-Disk -Number 1

Disks can contain both data and OEM partitions, and you can very easily remove them from the disk using the switch parameters -RemoveData and -RemoveOEM.

# Clear a target disk with data partitions
Clear-Disk -Number 1 –RemoveData

# Clear a disk regardless of whether it contains data or OEM partitions
Clear-Disk -Number 1 -RemoveData –RemoveOEM

Initialize a disk ^

A new disk or a cleaned disk using the cmdlet mentioned above is in an uninitialized state, and you have to initialize it first using the disk number of the target disk.

Initialize-Disk -Number 2

By default, this initializes all disks as GUID Partition Tables (GPTs) unless explicitly specified, and you can use the ‑PartitionStyle parameter to initialize a disk as a Master Boot Record (MBR).

Initialize-Disk 4 –PartitionStyle MBR

If the disk has recently just become present on the server, it will be in a raw partition style state. You can easily target and initialize such disks using the following command:

Get-Disk | Where-Object PartitionStyle –Eq 'RAW' | Initialize-Disk
Initialize the disk

Initialize the disk

Create a partition and volume ^

To create a partition, which is basically a block of data on the disk, you can run the New-Partition cmdlet with the ‑AssignDriveLetter and ‑UseMaximumSize switches to choose the available and allowed drive letter with the maximum size available on the disk.

New-Partition –DiskNumber 3 -AssignDriveLetter –UseMaximumSize

You can also explicitly specify the disk size and drive letter.

New-Partition –DiskNumber 4 -Size 150gb -DriveLetter h
Creating new partitions

Creating new partitions

After partitioning the disks, you can list them to see the current status:

# Listing partitions on specific disks
Get-Partition –DiskNumber 0,2,3
Getting the partitions

Getting the partitions

After creating the partitions, they are still not accessible from the File Explorer. You have to create new volumes in a format (like NTFS) that the operating system understands.

# List all volumes
Get-Volume

# Format volumes with NTFS
Format-Volume -DriveLetter F,H -FileSystem NTFS -Confirm:$false
Format the volumes

Format the volumes

Delete a partition ^

To delete any partition on a disk, you can target it with the disk number and then pipe it to the Remove-Partition cmdlet

# Delete a partition
Get-Partition –DiskNumber 2,3 | Remove-Partition -Confirm:$false
Deleting partitions

Deleting partitions

Conclusion ^

After presenting a storage disk on a Windows machine, it is very easy to initialize raw disks and bring them online using PowerShell. With just a few PowerShell cmdlets, you can also create partitions and volumes so they're accessible through the file system.

Subscribe to 4sysops newsletter!

Get-Disk |
Where-Object PartitionStyle -eq 'RAW' |
Initialize-Disk -PartitionStyle MBR -PassThru |
New-Partition -AssignDriveLetter -UseMaximumSize |
Format-Volume -FileSystem NTFS -Confirm:$false
Managing storage with PowerShell

Managing storage with PowerShell

+6
avataravataravatar
17 Comments
  1. Malte Schröder 3 years ago

    # List disks that are not system disks

    # to avoid accidently formatting your system drive

    Get-Disk | Where-Object IsSystem -eq $True

    Please change this to $False

    +4
    avatar
  2. everson 3 years ago

    thanks so much for this post

    0

  3. Mark Heath 2 years ago

    I'm trying to change a USB drive format from GPT to MBR (as my media player doesn't recognise GPT) I've tried Clear-Disk and Reset-Physicaldisk but Initilize-Disk keeps telling me that the disk is already initialized, how do I fix this?

    0

    • Use 

      Clear-Disk -RemoveData -RemoveOEM

      Then you can initialize it again.

      0

      • Mark 2 years ago

        I mentioned that I had done a Clear-Disk. I tried multiple options, none had removed the partition table.  I had to resort to using diskpart and interactively selecting the disk and performing a clean.

        I don't suppose anyone knows why Clear-disk did not work?

        0

        • Mark, I know you mentioned it. Thats why I tested it and it only did the desired job after adding the -RemoveOEM parameter. After that I was able to Initialize again. Would not advice something that I havent tried 🙂

          Why it doesnt work for you is hard to say .

          0

  4. Mark Heath 2 years ago
    PS C:\Users\mheath> Clear-Disk -Number 2 -RemoveData -RemoveOEM
    
    Confirm
    Are you sure you want to perform this action?
    This will erase all data on disk 2 "Sony Storage Media".
    [Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y
    PS C:\Users\mheath> Initialize-Disk -Number 2 -PartitionStyle gpt
    Initialize-Disk : The disk has already been initialized.
    Activity ID: {51ba9dd2-0923-0003-5b9f-ba512309d501}
    At line:1 char:1
    + Initialize-Disk -Number 2 -PartitionStyle gpt
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : NotSpecified: (StorageWMI:ROOT/Microsoft/Windows/Storage/MSFT_Disk) [Initialize-Disk], CimException
        + FullyQualifiedErrorId : StorageWMI 41001,Initialize-Disk
    
    PS C:\Users\mheath>

    what do I do to get to the bottom of this error?

    +1

    • I just added a new disk to Win 2012 R2, Initialized it, cleared with Clear-disk and then I can initialize it again.

      Can you check Disk Management GUI after you do clear-disk and confirm? The disk should go to Unknown status with red arrow down.

      I suggest to open a topic on PS Forum if you need further help.

      +1
      avatar
    • @Mark

      Did you check if your USB drive is not write-protected?

      0

      • Mark Heath 2 years ago

        err yes because this was the get-volume before the clear-disk. But shouldn't clear-disk report an error if that was the case?

        DriveLetter FriendlyName    FileSystemType DriveType HealthStatus OperationalStatus SizeRemaining      Size
        ----------- ------------    -------------- --------- ------------ ----------------- -------------      ----
        G           YELO_ABACUS     FAT32          Removable Healthy      OK                     13.63 GB  14.92 GB
        

        And this is it after the clear-disk

        
        DriveLetter FriendlyName    FileSystemType DriveType HealthStatus OperationalStatus SizeRemaining      Size
        ----------- ------------    -------------- --------- ------------ ----------------- -------------      ----
                                    Unknown        Removable Healthy      Unknown                     0 B       0 B
        

        I am looking for a way to change the partition type from MBR to GPT.

        Thanks for your time.

        0

  5. Christian Muehter 2 years ago

    I am using terraform and building a server with 6 drives not initialized, online or formatted.

     

    is there a way to do all that and assign drive letters using the full available space for each disk?

    +1

  6. Taha 2 years ago

    can you please show me a way to check following problems via powershell

    1.Check Storage Free Capacity and if not > 30% on all the Volumes it should send mail

    2 Check Data Transfer Rate between Volumes and if < 120 MB/s at any given time it should send mail  

    0

  7. HImanshuPathak 2 years ago

    Bro these codes are not working in WINPE mode.

    I have powershell support added in my winpe, all commands are working fine, but this clearing disk and volume are not working.

     

    Please assist

    +1

  8. Srinath Pelluri 2 years ago

    Has anyone has tried to obtain the list of the volume names against each partitions obtained ?

    Get-Volume shows the Volume Names as expected, but when ran with below command, the sort order does not seems to be correct.

    Get-Volume | Get-Partition

    Also, tried with below command and the sort order of list shown seems to wrong.

    Get-Partition |  Get-Volume

     

    The main aim is to print / obtain the list of volumes corresponding to the partitions in correct sort order, you nay create a small drive like HP_TOOLS volume with 2GB to check this.

    0

    • Chris 2 years ago

      Your question is a little old, but in case you never solved it, or if anyone comes here looking for the answer to your question, let me give some info here.

      The order of the volumes displayed by your two example command sequences will be indeterminate (that is, it could be anything) because you have not specified a sort order anywhere. This is important - never rely on any system to sort output unless you tell it to. I have seen identical servers built from identical AWS CloudFormation templates dump their disks in different orders if you don't specify otherwise. You didn't specify what you want the sort order to be, but whatever it is, just use the `Sort-Object` cmdlet on it. 

      The following example might be overkill with the Size expression in there, but I literally had this in VS Code right now so I just pasted what I was working with. Below the command you can see the current output from my laptop, which includes a USB drive and an SD card, but notice that everything is sorted in {DiskNumber, PartitionNumber} order ... because I told it to sort that way. 🙂

      Get-Partition | `
      Select-Object -Property `
        DiskNumber, `
        PartitionNumber, `
        DriveLetter, `
        @{Name="Size (GB)"; Expression={[Math]::Round($_.Size/(1024*1024*1024), 2)}}, `
        Type | `
      Sort-Object -Property DiskNumber, PartitionNumber | `
      Format-Table
      
      DiskNumber PartitionNumber DriveLetter Size (GB) Type
      ---------- --------------- ----------- --------- ----
               0               1                  0.49 System
               0               2                  0.12 Reserved
               0               3           C    921.59 Basic
               0               4                  9.31 Recovery
               1               1           E         0 Unknown
               1               2                 12.06 Unknown
               2               1           D      0.95 Logical
      0

  9. try it like this?

    $volumes = get-volume
    foreach($volume in $volumes){
      $volume.ObjectId
      $volume
      $volume | get-partition
    }
    

    with 

    get-volume | select * 

    you can see all the items, i dunno where it internally sorts on. I guess thats the reason it switches things around in output.

    0

  10. John Mon 7 months ago

    is there a PowerShell command that matches the RESCAN option within DiskPart.exe?

    0

Leave a reply

Please enclose code in pre tags

Your email address will not be published. Required fields are marked *

*

© 4sysops 2006 - 2021

CONTACT US

Please ask IT administration questions in the forums. Any other messages are welcome.

Sending

Log in with your credentials

or    

Forgot your details?

Create Account