skip to content

diskpart — Disk Partition Manager

Create, delete, format, extend, shrink, and assign drive letters to disk partitions from the Windows command prompt using an interactive or scripted REPL interface.

20 min read 108 snippets deep dive

diskpart — Disk Partition Manager#

What it is#

diskpart is a built-in Windows command-line tool for managing disks, partitions, and volumes. It operates as an interactive REPL: you enter diskpart, then issue commands at its DISKPART> prompt to list disks, select a target, and perform operations like creating or deleting partitions, formatting volumes, assigning drive letters, or converting disk types (MBR↔GPT). It can also run unattended from a script file passed via a pipe or < redirection. Requires elevation (Run as Administrator). The PowerShell equivalent is the Storage module (Get-Disk, New-Partition, Format-Volume).

Availability#

diskpart ships as C:\Windows\System32\diskpart.exe on Windows XP and later. Must be run as Administrator.

diskpart /?

Output:

Microsoft DiskPart version 10.0.22621.1

DISKPART> help

  ACTIVE      - Mark the selected partition as active.
  ADD         - Add a mirror to a simple volume.
  ASSIGN      - Assign a drive letter or mount point to the selected volume.
  ...

Syntax#

Interactive mode: enter commands at the DISKPART> prompt. Script mode: diskpart /s script.txt.

diskpart

Output:

Microsoft DiskPart version 10.0.22621.1

Copyright (C) Microsoft Corporation.
On computer: MYHOST

DISKPART>

Essential commands#

CommandMeaning
list diskShow all physical disks
list volumeShow all volumes (drive letters)
list partitionShow partitions on the selected disk
select disk NSet focus to disk N
select volume NSet focus to volume N
select partition NSet focus to partition N on the selected disk
detail diskShow details about the selected disk
detail volumeShow details about the selected volume
create partition primary [size=MB]Create a primary partition
create partition extended [size=MB]Create an extended partition
create partition logical [size=MB]Create a logical partition inside extended
format fs=ntfs quick [label="Name"]Quick-format selected volume
assign letter=XAssign drive letter X
remove letter=XRemove drive letter assignment
delete partition [override]Delete the selected partition
delete volumeDelete the selected volume
extend [size=MB]Extend volume into available contiguous space
shrink desired=MBShrink volume by specified amount
cleanRemove all partition info from selected disk (destructive)
convert gptConvert MBR disk to GPT
convert mbrConvert GPT disk to MBR
activeMark partition as active (bootable)
exitQuit diskpart

Listing disks and volumes#

list disk and list volume are always the first commands to run — they show available targets and their current state.

diskpart

Output:

DISKPART>
list disk

Output:


  Disk ###  Status         Size     Free     Dyn  Gpt
  --------  -------------  -------  -------  ---  ---
  Disk 0    Online          476 GB      0 B        *
  Disk 1    Online         1863 GB   500 GB        *
list volume

Output:


  Volume ###  Ltr  Label        Fs     Type        Size     Status     Info
  ----------  ---  -----------  -----  ----------  -------  ---------  --------
  Volume 0     C   System       NTFS   Partition    475 GB  Healthy    Boot
  Volume 1     D   Data         NTFS   Partition   1363 GB  Healthy
  Volume 2         EFI          FAT32  Partition    100 MB  Healthy    System

Selecting a target#

Before any operation, select the disk, volume, or partition you want to act on. The * marker in list output shows the currently selected item.

select disk 1

Output:

Disk 1 is now the selected disk.
list partition

Output:


  Partition ###  Type              Size     Offset
  -------------  ----------------  -------  -------
  Partition 1    Primary           1363 GB  1024 KB

Creating a partition and formatting#

To initialise a new disk: select it, clean it (removes all partition tables), create a partition, format it, and assign a letter.

select disk 1

Output:

Disk 1 is now the selected disk.
clean

Output:

DiskPart succeeded in cleaning the disk.
create partition primary

Output:

DiskPart succeeded in creating the specified partition.
format fs=ntfs label="Data" quick

Output:

  100 percent completed

DiskPart successfully formatted the volume.
assign letter=E

Output:

DiskPart successfully assigned the drive letter or mount point.

Extending a volume#

extend grows the selected volume into contiguous unallocated space on the same disk. If no size is specified, all available space is consumed.

select volume 1

Output:

Volume 1 is the selected volume.
extend size=10240

Output:

DiskPart successfully extended the volume.

Shrinking a volume#

shrink reduces the selected volume by the requested amount, creating unallocated space that can then be used for a new partition. Actual shrinkage may be less than requested if unmovable data (page file, system files) occupies the end of the volume.

select volume 0

Output:

Volume 0 is the selected volume.
shrink desired=20480

Output:

DiskPart successfully shrunk the volume by:  20480 MB

Converting MBR to GPT#

convert gpt rewrites the partition table format. The disk must have no partitions (run clean first, or use the non-destructive mbr2gpt tool). Required for disks over 2 TB and for UEFI booting.

select disk 1

Output:

Disk 1 is now the selected disk.
convert gpt

Output:

DiskPart successfully converted the selected disk to GPT format.

Running diskpart from a script#

diskpart /s script.txt reads commands line by line without the interactive prompt — essential for unattended imaging and deployment.

diskpart /s format_usb.txt

Output:

DiskPart successfully cleaned the disk.
DiskPart succeeded in creating the specified partition.
DiskPart successfully formatted the volume.
DiskPart successfully assigned the drive letter or mount point.

Example format_usb.txt:

select disk 1
clean
create partition primary
format fs=fat32 label="USB" quick
assign letter=F
exit

Output: (embedded in the script content above — no separate output block needed)

Complete command reference#

Every documented command. Most apply to one of three “focus” levels — disk, partition, or volume — and require selecting the target first.

CommandFocus neededNotes
activepartitionMark partition active (BIOS/MBR boot).
add disk=NvolumeAdd a mirror to a simple volume (Dynamic disks).
assign letter=X [mount=path]volume / partitionAssign drive letter or mount-point path.
`attributes disk [setclear] [readonly]`disk
`attributes volume [setclear] [hiddenreadonly
`automount [enabledisablescrub]`
break disk=N [nokeep]volumeBreak a mirror.
clean [all]diskWipe partition table; all zeroes every sector.
compact vdiskvdiskCompact a dynamically expanding VHD.
`convert [mbrgptdynamic
`create partition [primaryextendedlogical
`create volume [simplestriperaid
`create vdisk file=“path” [type=expandablefixed] [maximum=MB] [parent=path]`none
delete disk [noerr] [override]diskRemove a missing dynamic disk.
delete partition [override] [noerr]partitionDelete partition; override allows protected partitions.
delete volumevolumeDelete a volume.
detach vdiskvdiskDetach (close) a VHD.
`detail [diskpartitionvolume
exitnoneQuit diskpart.
expand vdisk maximum=MBvdiskGrow a VHD’s maximum size.
extend [size=N] [disk=N] [noerr] [filesystem]partition / volumeExtend by N MB or all free space; filesystem also grows NTFS.
filesystemsvolumeList supported file systems for the volume.
`format [fs=fat32ntfsexfat
gpt attributes=hexpartition (GPT)Set GPT partition attribute bits.
help [command]noneShow help; help <command> shows command-specific help.
importdiskImport a foreign dynamic disk.
inactivepartitionClear active flag.
`list [diskpartitionvolume
merge vdisk depth=NvdiskMerge differencing VHD up N levels.
offline diskdiskTake a disk offline.
offline volumevolumeTake a volume offline.
online disk [noerr]diskBring a disk online.
online volumevolumeBring a volume online.
recoverdiskRefresh state of a Dynamic disk pack.
remnoneComment (script files).
`remove [letter=Xmount=pathall
repair disk=NvolumeReplace a failed mirror member.
rescannoneRescan the storage stack for added/removed disks.
retainvolumeReserve a partition entry for a simple volume (boot).
`san [policy=onlineallofflineallofflineshared
`select [diskpartitionvolume
`set id=GUIDhex [override]`partition
`setid=GUIDhex`partition
shrink [desired=N] [minimum=N] [nowait] [noerr]volume / partitionShrink by up to N MB.
`uniqueid disk [id=hexGUID]`disk

Launching diskpart in script mode#

Script mode is the unattended workhorse — perfect for OS deployment, automated re-imaging, and bulk USB key prep. Each line of the script is a single diskpart command; comments use rem.

diskpart /s D:\Scripts\format_usb.txt

Output:

Microsoft DiskPart version 10.0.26100.1

Copyright (C) Microsoft Corporation.
On computer: MYHOST

DiskPart succeeded in cleaning the disk.
DiskPart succeeded in creating the specified partition.
DiskPart marked the current partition as active.
DiskPart successfully formatted the volume.
DiskPart successfully assigned the drive letter or mount point.

Wrap the script in retry logic and tee the log to a dated file:

@echo off
set LOG=C:\Logs\diskpart_%COMPUTERNAME%_%DATE:~10,4%%DATE:~4,2%%DATE:~7,2%.log
echo Running %~dp0format_usb.txt > %LOG%
diskpart /s %~dp0format_usb.txt >> %LOG% 2>&1
if errorlevel 1 (
    echo DISKPART FAILED — see %LOG%
    exit /b 1
)
echo Success.

Output:

Success.

GPT partition types#

set id= changes the partition type GUID on a GPT disk. The well-known GUIDs let you create partitions that Windows / WinPE / OEM tools will recognize on inspection.

RoleGPT GUID
Microsoft Basic Data (default for NTFS/FAT)ebd0a0a2-b9e5-4433-87c0-68b6b72699c7
EFI System Partition (ESP)c12a7328-f81f-11d2-ba4b-00a0c93ec93b
Microsoft Reserved (MSR)e3c9e316-0b5c-4db8-817d-f92df00215ae
Windows Recovery Environmentde94bba4-06d1-4d40-a16a-bfd50179d6ac
Linux filesystem0fc63daf-8483-4772-8e79-3d69d8477de4
Linux LVMe6d6d379-f507-44c2-a23c-238f2a3df928
BIOS Boot (GRUB)21686148-6449-6e6f-744e-656564454649
select disk 0
select partition 1
set id=c12a7328-f81f-11d2-ba4b-00a0c93ec93b

Output:

DiskPart successfully set the partition ID.

On MBR disks set id= takes a 2-digit hex value: 07 for IFS/NTFS, 0c for FAT32 LBA, 27 for hidden NTFS, 83 for Linux, 82 for Linux swap.

Building a UEFI/GPT system layout from scratch#

A standard Windows 11 UEFI install lays out four partitions: an EFI System Partition, a Microsoft Reserved partition, the primary OS partition, and a recovery partition at the end. The following script reproduces it on a target disk and is the same recipe used by Windows Setup under the hood.

rem File: setup_uefi.txt — run from WinPE
select disk 0
clean
convert gpt

rem 1. EFI System Partition — 260 MB, FAT32, hidden
create partition efi size=260
format fs=fat32 quick label="System"
assign letter=S

rem 2. Microsoft Reserved — 16 MB, no file system
create partition msr size=16

rem 3. Windows OS partition — the rest minus 1 GB recovery
create partition primary
shrink minimum=1024
format fs=ntfs quick label="Windows"
assign letter=W

rem 4. Recovery partition at the tail
create partition primary
format fs=ntfs quick label="Recovery"
assign letter=R
set id=de94bba4-06d1-4d40-a16a-bfd50179d6ac
gpt attributes=0x8000000000000001
exit

Output:

DiskPart succeeded in cleaning the disk.
DiskPart successfully converted the selected disk to GPT format.
DiskPart succeeded in creating the specified partition.
  100 percent completed
DiskPart successfully formatted the volume.
DiskPart successfully assigned the drive letter or mount point.
DiskPart succeeded in creating the specified partition.
DiskPart succeeded in creating the specified partition.
DiskPart successfully shrunk the volume by:  1024 MB
  100 percent completed
DiskPart successfully formatted the volume.
DiskPart successfully assigned the drive letter or mount point.
DiskPart succeeded in creating the specified partition.
  100 percent completed
DiskPart successfully formatted the volume.
DiskPart successfully assigned the drive letter or mount point.
DiskPart successfully set the partition ID.
DiskPart successfully assigned the attributes.

VHD/VHDX management#

diskpart natively creates, attaches, expands, compacts, and merges VHD/VHDX files — useful for sandboxing, golden-image work, and Hyper-V parent disks.

create vdisk file="C:\VMs\lab.vhdx" maximum=51200 type=expandable
attach vdisk
create partition primary
format fs=ntfs quick label="Lab"
assign letter=Q
exit

Output:

  100 percent completed
DiskPart successfully created the virtual disk file.
DiskPart successfully attached the virtual disk file.
DiskPart succeeded in creating the specified partition.
  100 percent completed
DiskPart successfully formatted the volume.
DiskPart successfully assigned the drive letter or mount point.
rem Compact (only effective on dynamically expanding VHDs that contain freed space)
select vdisk file="C:\VMs\lab.vhdx"
attach vdisk readonly
compact vdisk
detach vdisk

Output:

DiskPart successfully attached the virtual disk file.
  100 percent completed
DiskPart successfully compacted the virtual disk file.
DiskPart successfully detached the virtual disk file.
rem Expand the maximum size of an existing VHD
select vdisk file="C:\VMs\lab.vhdx"
expand vdisk maximum=102400
attach vdisk
select partition 1
extend filesystem
detach vdisk

Output:

  100 percent completed
DiskPart successfully expanded the virtual disk file.
DiskPart successfully attached the virtual disk file.
DiskPart successfully extended the file system on the volume.
DiskPart successfully detached the virtual disk file.

PowerShell equivalents — the Storage module#

PowerShell’s Storage module exposes the same plumbing through real cmdlets — they return objects, integrate with pipelines, and use named parameters instead of focus-and-act state. Prefer them in scripts.

# Inventory: disks, partitions, volumes
Get-Disk
Get-Partition
Get-Volume

Output:

Number Friendly Name           Serial Number     HealthStatus  OperationalStatus Total Size Partition Style
------ -------------           -------------     ------------  ----------------- ---------- ---------------
     0 Samsung SSD 990 PRO     S5K8NS0R012345    Healthy       Online              476.94 GB GPT
     1 WDC WD40EFRX-68N32N0    WD-WCC7K1234567   Healthy       Online             3725.91 GB GPT
# Initialize a new disk as GPT, single NTFS partition, drive letter G:
Initialize-Disk -Number 1 -PartitionStyle GPT -PassThru |
    New-Partition -UseMaximumSize -DriveLetter G |
    Format-Volume -FileSystem NTFS -NewFileSystemLabel 'Data' -Confirm:$false

Output:

DriveLetter       FileSystemLabel  FileSystemType DriveType HealthStatus OperationalStatus SizeRemaining       Size
-----------       ---------------  -------------- --------- ------------ ----------------- -------------       ----
G                 Data             NTFS           Fixed     Healthy      OK                3.62 TB             3.63 TB
# Resize partitions — both directions
Resize-Partition -DriveLetter G -Size 1TB
Resize-Partition -DriveLetter G -Size ((Get-PartitionSupportedSize -DriveLetter G).SizeMax)

Output:

(no output on success)
# Set / change a drive letter
Set-Partition -DriveLetter G -NewDriveLetter H

# Hide a partition (no drive letter)
Get-Partition -DriveLetter G | Remove-PartitionAccessPath -AccessPath 'G:\'

Output:

(no output on success)
# Eject (offline) a disk safely before unplugging
Get-Disk -Number 2 | Set-Disk -IsOffline $true

Output:

(no output on success)
# Mount a VHD
Mount-DiskImage -ImagePath C:\VMs\lab.vhdx -StorageType VHDX -PassThru |
    Get-Disk |
    Get-Partition |
    Where-Object Type -eq 'Basic'

Output:

DiskPath        : \\.\PHYSICALDRIVE2
Attached        : True
ImagePath       : C:\VMs\lab.vhdx
Number          : 2
...

   DiskNumber Partition Number DriveLetter Offset                Size Type
   ---------- ---------------- -----------                  ---- ----
            2                1           Q  16777216           50 GB Basic
# Dismount the VHD
Dismount-DiskImage -ImagePath C:\VMs\lab.vhdx

Output:

Attached  : False
ImagePath : C:\VMs\lab.vhdx

Storage Spaces from the command line#

For modern pooled storage Microsoft has moved away from diskpart’s legacy “Dynamic Disks” toward Storage Spaces — pools of physical disks carved into resilient virtual disks. Manage them with the Storage PowerShell module.

# Inventory pool-eligible disks
Get-PhysicalDisk -CanPool $true |
    Select FriendlyName, MediaType, Size, BusType, HealthStatus

Output:

FriendlyName             MediaType          Size BusType HealthStatus
------------             ---------          ---- ------- ------------
WDC WD40EFRX-68N32N0     HDD       4000787030016 SATA    Healthy
WDC WD40EFRX-68N32N0     HDD       4000787030016 SATA    Healthy
Samsung SSD 870 EVO 1TB  SSD       1000204886016 SATA    Healthy
# Create a storage pool from those disks
New-StoragePool -FriendlyName 'FleetPool' `
                -StorageSubSystemFriendlyName 'Windows Storage*' `
                -PhysicalDisks (Get-PhysicalDisk -CanPool $true)

# Create a mirrored virtual disk on top
New-VirtualDisk -StoragePoolFriendlyName FleetPool `
                -FriendlyName Mirror1 `
                -ResiliencySettingName Mirror `
                -Size 1TB |
    Get-Disk |
    Initialize-Disk -PartitionStyle GPT -PassThru |
    New-Partition -UseMaximumSize -DriveLetter S |
    Format-Volume -FileSystem ReFS -NewFileSystemLabel 'StoragePool' -Confirm:$false

Output:

FriendlyName Size Status HealthStatus FileSystem DriveLetter
------------ ---- ------ ------------ ---------- -----------
Mirror1      1TB  OK     Healthy      ReFS       S
# Tear it back down
Remove-VirtualDisk -FriendlyName Mirror1 -Confirm:$false
Remove-StoragePool -FriendlyName FleetPool -Confirm:$false

Output:

(no output on success)

NTFS vs ReFS at format time#

diskpart format and Format-Volume both accept fs=refs (or fs=ntfs, fs=fat32, fs=exfat). Pick one based on the workload — there is no in-place conversion between NTFS and ReFS.

PropertyNTFSReFS
Max volume size256 TB (4k clusters) / 8 PB (64k)4.7 ZB (theoretical)
Max file size256 TB / 8 PB16 EB
BootableYesNo
Shadow Copies / VSSYesLimited
BitLockerYesYes
CompressionYes (NTFS LZX/Xpress)No
Encryption (EFS)YesNo
Sparse filesYesYes
Hard linksYesYes
Block cloneNoYes (COW)
Integrity streamsNoYes
Auto-repairOffline (chkdsk)Online (Repair-FileIntegrity)
DedupYesYes (Server only)
QuotasYesNo
rem ReFS format from diskpart (Windows Server / Pro for Workstations)
select volume 4
format fs=refs label="DataLake" quick

Output:

  100 percent completed
DiskPart successfully formatted the volume.
# ReFS with integrity streams enforced and 64k clusters (best for large files)
Format-Volume -DriveLetter R -FileSystem ReFS -AllocationUnitSize 65536 `
              -SetIntegrityStreams $true -NewFileSystemLabel 'DataLake' -Confirm:$false

Output:

DriveLetter FileSystemLabel  FileSystemType DriveType HealthStatus OperationalStatus SizeRemaining   Size
----------- ---------------  -------------- --------- ------------ ----------------- -------------   ----
R           DataLake         ReFS           Fixed     Healthy      OK                3.99 TB         4.00 TB

SAN policy for new disks#

On Server SKUs the SAN policy controls whether newly-presented disks come up Online (and read/write) or Offline. Misconfiguration here is a common cluster footgun.

diskpart
san

Output:

SAN Policy  : Offline Shared
rem Force every new disk online (laptop / desktop default)
san policy=onlineall

Output:

DiskPart successfully changed the SAN policy for the current operating system.
rem Server best practice — keep shared SAN disks offline until explicitly claimed
san policy=offlineshared

Output:

DiskPart successfully changed the SAN policy for the current operating system.
# PowerShell equivalent
Get-StorageSetting | Select NewDiskPolicy
Set-StorageSetting -NewDiskPolicy OfflineShared

Output:

NewDiskPolicy
-------------
OfflineShared

Recovering boot/EFI partitions#

When the BCD or EFI System Partition is damaged, diskpart is the staging tool: assign a letter to the ESP so bcdboot can rewrite the loader files.

rem Run from WinRE / WinPE
select disk 0
list partition
select partition 1   rem the EFI System Partition
assign letter=S
exit

Output:

DiskPart successfully assigned the drive letter or mount point.
rem Rewrite the boot files for the Windows install on C:
bcdboot C:\Windows /s S: /f UEFI

Output:

Boot files successfully created.

For the full BCD edit flow see sections/windows/bcdedit.

Common pitfalls#

  1. clean is irreversible — it destroys all partition tables on the selected disk; always triple-check list disk and select disk before running clean.
  2. Operating on the wrong disk — diskpart numbers disks dynamically; a disk that was Disk 1 yesterday may be Disk 2 after a reboot if disks were added/removed. Always verify with list disk and detail disk.
  3. extend requires contiguous free space — the unallocated space must be immediately after the partition on the same disk; non-contiguous free space requires third-party tools.
  4. shrink may not shrink as much as requested — immovable files (hibernation file, VSS snapshots) at the end of the volume limit how much can be reclaimed; disable hiberfil.sys (powercfg /h off) first.
  5. GPT conversion requires no partitionsconvert gpt fails if the disk has partitions; back up data, run clean, convert, then recreate partitions.
  6. Requires elevation — all diskpart commands require Administrator privileges; launch cmd.exe as Administrator before starting diskpart.
  7. Focus is not persistent across instances — every new diskpart invocation starts with no focus; scripts must re-select before each operation.
  8. format defaults to a slow full format — always add quick unless you specifically want a surface scan.
  9. set id= on EFI/MSR partitions can break boot — only change partition type GUIDs on data partitions; the EFI System Partition and Microsoft Reserved GUIDs are required by Windows.
  10. MBR disks cap at 2 TB — beyond 2 TB the extra space is unaddressable; convert to GPT (requires clean disk) before partitioning.
  11. Dynamic Disks are legacy — use Storage Spaces for new resilient layouts; convert dynamic is mostly maintained for upgrade scenarios.
  12. compact vdisk requires the VHD to be attached read-only and not in use — attaching the VHD read-write and then compacting fails; the VHD must also have been zeroed out first (use sdelete -z inside the guest) for compaction to reclaim space.
  13. SAN policy persists — changing the SAN policy on a server affects every new disk discovery, including hot-add scenarios; document the policy in the build manifest.
  14. format fs=refs on the boot disk fails — ReFS is not bootable; only NTFS is supported for the OS partition.
  15. BitLocker-protected volumes cannot be resized without unlockingshrink and extend return errors; suspend BitLocker (manage-bde -protectors -disable) or unlock the volume before resizing.

Sources#

References consulted while writing this article. Links open in a new tab.

Real-world recipes#

Initialise a new data disk end-to-end#

select disk 2
clean
convert gpt
create partition primary
format fs=ntfs label="Backup" quick
assign letter=G
exit

Output:

DiskPart succeeded in cleaning the disk.
DiskPart successfully converted the selected disk to GPT format.
DiskPart succeeded in creating the specified partition.
DiskPart successfully formatted the volume.
DiskPart successfully assigned the drive letter or mount point.

Remove a drive letter assignment#

diskpart

Output:

DISKPART>
select volume 3

Output:

Volume 3 is the selected volume.
remove letter=H

Output:

DiskPart successfully removed the drive letter or mount point.

USB installer prep in one script#

A reusable script for turning a USB stick into a UEFI-bootable Windows installer.

rem File: make_winusb.txt
list disk
select disk 2
clean
convert gpt
create partition primary size=512
format fs=fat32 quick label="WINSETUP"
assign letter=U
create partition primary
format fs=ntfs quick label="WINIMAGE"
assign letter=W
exit
diskpart /s C:\Scripts\make_winusb.txt
robocopy D:\ U:\ /E /XD sources
mkdir U:\sources
copy /b D:\sources\boot.wim U:\sources\
robocopy D:\sources W:\sources /E

Output:

DiskPart succeeded in cleaning the disk.
DiskPart successfully converted the selected disk to GPT format.
...
DiskPart successfully assigned the drive letter or mount point.

   ROBOCOPY     ::     Robust File Copy for Windows
-------------------------------------------------------------------------------
   Total    Copied   Skipped  Mismatch    FAILED    Extras
    Dirs :        8         8         0         0         0         0
   Files :     1438      1438         0         0         0         0

Full PowerShell setup of a new data drive#

End-to-end provisioning of a disk: initialize, partition, format, assign letter — without ever entering the diskpart REPL.

$diskNumber = 2
$letter     = 'E'
$label      = 'Backup'

Get-Disk $diskNumber | Where-Object PartitionStyle -eq 'RAW' |
    Initialize-Disk -PartitionStyle GPT -PassThru |
    New-Partition -UseMaximumSize -DriveLetter $letter |
    Format-Volume -FileSystem NTFS -NewFileSystemLabel $label -AllocationUnitSize 4096 -Confirm:$false

Get-Volume -DriveLetter $letter | Format-List DriveLetter, FileSystemLabel, FileSystemType, SizeRemaining, Size

Output:

DriveLetter      : E
FileSystemLabel  : Backup
FileSystemType   : NTFS
SizeRemaining    : 3.62 TB
Size             : 3.63 TB

Online → offline → physically remove → online again#

The supported eject sequence for a hot-swap drive without unmounting through the GUI.

# Take the disk offline (safe for hot removal)
Set-Disk -Number 2 -IsOffline $true

# ... physically swap or reseat the disk ...

# Rescan to pick up the change
Update-HostStorageCache

# Bring back online
Set-Disk -Number 2 -IsOffline $false

Output:

(no output on success)

Mount an ISO/VHD without the GUI#

Mount-DiskImage is the supported one-shot for both ISO and VHD/VHDX files.

$img = Mount-DiskImage -ImagePath D:\ISOs\Windows.iso -PassThru
($img | Get-Volume).DriveLetter

Output:

H
# Dismount when done
Dismount-DiskImage -ImagePath D:\ISOs\Windows.iso

Output:

Attached  : False
ImagePath : D:\ISOs\Windows.iso