How to Create a New Partition with DiskPart in Batch Script
When a disk has unallocated space, either from a fresh initialization or from deleting an old partition, you need to create a new volume before you can store anything on it. In a server environment, this might mean creating separate partitions for applications, user data, and log files. Rather than using the graphical Disk Management snap-in, a Batch script can use DiskPart to create partitions with precise sizes, assign drive letters, and format them, all in one automated pass.
This guide will explain how to create partitions programmatically using DiskPart from Batch.
Method 1: Create a Single Partition (Full Remaining Space)
This method creates one partition that consumes all available unallocated space on the disk. This is the most common scenario for a dedicated data or backup drive.
Implementation
@echo off
setlocal
set "DiskNum=%~1"
set "Letter=%~2"
set "Label=%~3"
if "%DiskNum%"=="" (
echo Usage: %~nx0 ^<disk_number^> [drive_letter] [volume_label]
echo.
echo Creates a single NTFS partition using all unallocated space.
echo.
echo Examples:
echo %~nx0 1
echo %~nx0 2 E DataDrive
echo.
echo Run "diskpart" then "list disk" to identify disk numbers.
endlocal
exit /b 1
)
if "%Letter%"=="" set "Letter=E"
if "%Label%"=="" set "Label=Data"
:: Verify admin privileges
net session >nul 2>&1
if errorlevel 1 (
echo [ERROR] DiskPart requires administrator privileges. >&2
endlocal
exit /b 1
)
:: Safety: refuse disk 0
if "%DiskNum%"=="0" (
echo [ERROR] Refusing to modify Disk 0 (OS drive^). >&2
endlocal
exit /b 1
)
:: Verify the disk exists and check for unallocated space
for /f "tokens=1-3 delims=|" %%a in (
'powershell -NoProfile -Command ^
"$d = Get-Disk -Number %DiskNum% -ErrorAction SilentlyContinue;" ^
"if (-not $d) { Write-Output ''NOT_FOUND|0|0''; exit 1 };" ^
"$totalGB = [math]::Round($d.Size / 1GB, 1);" ^
"$allocatedBytes = ($d | Get-Partition -ErrorAction SilentlyContinue | Measure-Object Size -Sum).Sum;" ^
"if (-not $allocatedBytes) { $allocatedBytes = 0 };" ^
"$freeGB = [math]::Round(($d.Size - $allocatedBytes) / 1GB, 1);" ^
"Write-Output \"$($d.FriendlyName)|$totalGB|$freeGB\""'
) do (
set "DiskName=%%a"
set "TotalGB=%%b"
set "FreeGB=%%c"
)
if "%DiskName%"=="NOT_FOUND" (
echo [ERROR] Disk %DiskNum% does not exist. >&2
endlocal
exit /b 1
)
echo [INFO] Disk %DiskNum%: %DiskName% (%TotalGB% GB total, ~%FreeGB% GB unallocated^)
:: Check if there's meaningful unallocated space
powershell -NoProfile -Command "if (%FreeGB% -lt 0.1) { exit 1 } else { exit 0 }" >nul 2>&1
if errorlevel 1 (
echo [ERROR] No unallocated space available on Disk %DiskNum%. >&2
echo Use "list partition" in DiskPart to see existing partitions. >&2
endlocal
exit /b 1
)
:: Check drive letter availability
if exist %Letter%:\ (
echo [ERROR] Drive letter %Letter%: is already in use. >&2
endlocal
exit /b 1
)
echo [ACTION] Creating partition on Disk %DiskNum% (all free space^)...
echo [INFO] Drive letter: %Letter%: Label: "%Label%" Filesystem: NTFS
set "DPScript=%TEMP%\dp_newpart_%RANDOM%.txt"
(
echo select disk %DiskNum%
echo create partition primary
echo format fs=ntfs label="%Label%" quick
echo assign letter=%Letter%
) > "%DPScript%"
diskpart /s "%DPScript%" >nul 2>&1
set "DPResult=%errorlevel%"
del "%DPScript%" 2>nul
if %DPResult% neq 0 (
echo [ERROR] Partition creation failed. >&2
echo Possible causes: >&2
echo - Disk has no unallocated space >&2
echo - Disk is read-only or in use >&2
echo - Maximum partition count reached (4 for MBR^) >&2
endlocal
exit /b 1
)
:: Verify the drive is accessible
timeout /t 2 >nul
if exist %Letter%:\ (
echo [OK] Partition created and mounted at %Letter%:\
echo [OK] NTFS, label "%Label%"
) else (
echo [WARNING] DiskPart reported success but %Letter%:\ is not accessible. >&2
echo Check Disk Management for details. >&2
)
endlocal
exit /b 0
Why create partition primary without size=:
When the size= parameter is omitted, DiskPart creates a partition using ALL remaining unallocated space on the disk. This is the simplest approach for single-partition disks and for the last partition in a multi-partition layout.
Method 2: Create a Partition with a Specific Size
Use this to carve out a portion of the disk, leaving the remaining space unallocated for future partitions.
@echo off
setlocal
set "DiskNum=%~1"
set "SizeMB=%~2"
set "Letter=%~3"
set "Label=%~4"
if "%SizeMB%"=="" (
echo Usage: %~nx0 ^<disk_number^> ^<size_mb^> [drive_letter] [label]
echo.
echo Creates a partition of the specified size in megabytes.
echo.
echo Size reference:
echo 10 GB = 10240 MB
echo 50 GB = 51200 MB
echo 100 GB = 102400 MB
echo 500 GB = 512000 MB
echo.
echo Example: %~nx0 1 51200 F Apps
echo (Creates a 50 GB partition on Disk 1 as F: with label "Apps"^)
endlocal
exit /b 1
)
if "%Letter%"=="" set "Letter=F"
if "%Label%"=="" set "Label=Data"
net session >nul 2>&1
if errorlevel 1 (
echo [ERROR] Administrator privileges required. >&2
endlocal
exit /b 1
)
if "%DiskNum%"=="0" (
echo [ERROR] Refusing to modify Disk 0. >&2
endlocal
exit /b 1
)
:: Verify disk exists
for /f "delims=" %%n in (
'powershell -NoProfile -Command ^
"$d = Get-Disk -Number %DiskNum% -ErrorAction SilentlyContinue;" ^
"if ($d) { $d.FriendlyName } else { Write-Output ''NOT_FOUND'' }"'
) do set "DiskName=%%n"
if "%DiskName%"=="NOT_FOUND" (
echo [ERROR] Disk %DiskNum% not found. >&2
endlocal
exit /b 1
)
if exist %Letter%:\ (
echo [ERROR] Drive letter %Letter%: is already in use. >&2
endlocal
exit /b 1
)
:: Convert MB to human-readable GB for display
for /f "delims=" %%g in (
'powershell -NoProfile -Command "[math]::Round(%SizeMB% / 1024, 1)"'
) do set "SizeGB=%%g"
echo [ACTION] Creating %SizeGB% GB (%SizeMB% MB^) partition on Disk %DiskNum%...
echo [INFO] Drive: %Letter%: Label: "%Label%"
set "DPScript=%TEMP%\dp_sizedpart_%RANDOM%.txt"
(
echo select disk %DiskNum%
echo create partition primary size=%SizeMB%
echo format fs=ntfs label="%Label%" quick
echo assign letter=%Letter%
) > "%DPScript%"
diskpart /s "%DPScript%" >nul 2>&1
set "DPResult=%errorlevel%"
del "%DPScript%" 2>nul
if %DPResult% neq 0 (
echo [ERROR] Partition creation failed. >&2
echo The disk may not have %SizeGB% GB of unallocated space. >&2
endlocal
exit /b 1
)
timeout /t 2 >nul
if exist %Letter%:\ (
echo [OK] %SizeGB% GB partition created at %Letter%:\
) else (
echo [WARNING] Partition may not have been created successfully. >&2
)
endlocal
exit /b 0
Size reference table:
| Desired Size | size= Value (MB) |
|---|---|
| 10 GB | 10240 |
| 25 GB | 25600 |
| 50 GB | 51200 |
| 100 GB | 102400 |
| 200 GB | 204800 |
| 500 GB | 512000 |
| 1 TB | 1048576 |
DiskPart's size= parameter is always in megabytes (1 GB = 1024 MB).
Method 3: Multi-Partition Server Layout
For server deployments, a professional disk layout separates applications, user data, and logs onto different partitions. This method creates a complete multi-volume layout on a single disk.
@echo off
setlocal EnableDelayedExpansion
set "DiskNum=%~1"
if "%DiskNum%"=="" (
echo Usage: %~nx0 ^<disk_number^>
echo.
echo Creates a professional server partition layout:
echo D: Applications (100 GB^)
echo E: User Data (200 GB^)
echo L: Logs (remaining space^)
echo.
echo The disk will be cleaned and initialized as GPT.
echo *** ALL EXISTING DATA ON THE DISK WILL BE ERASED ***
echo.
echo Example: %~nx0 1
endlocal
exit /b 1
)
net session >nul 2>&1
if errorlevel 1 (
echo [ERROR] Administrator privileges required. >&2
endlocal
exit /b 1
)
if "%DiskNum%"=="0" (
echo [ERROR] Refusing to modify Disk 0 (OS drive^). >&2
endlocal
exit /b 1
)
:: Verify disk exists and get size
for /f "tokens=1-2 delims=|" %%a in (
'powershell -NoProfile -Command ^
"$d = Get-Disk -Number %DiskNum% -ErrorAction SilentlyContinue;" ^
"if (-not $d) { Write-Output ''NOT_FOUND|0''; exit 1 };" ^
"Write-Output \"$($d.FriendlyName)|$([math]::Round($d.Size/1GB,1))\""'
) do (
set "DiskName=%%a"
set "DiskSizeGB=%%b"
)
if "%DiskName%"=="NOT_FOUND" (
echo [ERROR] Disk %DiskNum% not found. >&2
endlocal
exit /b 1
)
:: Verify minimum size (need at least ~350 GB for this layout)
powershell -NoProfile -Command "if (%DiskSizeGB% -lt 350) { exit 1 } else { exit 0 }" >nul 2>&1
if errorlevel 1 (
echo [ERROR] Disk %DiskNum% is too small (%DiskSizeGB% GB^). >&2
echo This layout requires at least 350 GB. >&2
endlocal
exit /b 1
)
:: Check drive letter availability
for %%L in (D E L) do (
if exist %%L:\ (
echo [ERROR] Drive letter %%L: is already in use. >&2
endlocal
exit /b 1
)
)
:: Show plan and confirm
echo ============================================================
echo MULTI-PARTITION LAYOUT - DISK %DiskNum%
echo ============================================================
echo.
echo Disk: !DiskName! (!DiskSizeGB! GB^)
echo.
echo Layout:
echo D: Applications 100 GB NTFS
echo E: UserData 200 GB NTFS
echo L: Logs (remaining space^) NTFS
echo.
echo The disk will be CLEANED and initialized as GPT.
echo *** ALL EXISTING DATA WILL BE ERASED ***
echo.
echo ============================================================
set /p "Confirm=Type SETUP to proceed: "
if /i not "%Confirm%"=="SETUP" (
echo [INFO] Cancelled. No changes were made.
endlocal
exit /b 0
)
echo.
echo [ACTION] Setting up multi-partition layout on Disk %DiskNum%...
set "DPScript=%TEMP%\dp_multi_%RANDOM%.txt"
(
echo select disk %DiskNum%
echo clean
echo convert gpt
echo create partition primary size=102400
echo format fs=ntfs label="Applications" quick
echo assign letter=D
echo create partition primary size=204800
echo format fs=ntfs label="UserData" quick
echo assign letter=E
echo create partition primary
echo format fs=ntfs label="Logs" quick
echo assign letter=L
) > "%DPScript%"
diskpart /s "%DPScript%" >nul 2>&1
set "DPResult=%errorlevel%"
del "%DPScript%" 2>nul
if %DPResult% neq 0 (
echo [ERROR] Multi-partition setup failed. >&2
echo Check Disk Management for the current state of Disk %DiskNum%. >&2
endlocal
exit /b 1
)
:: Verify all three drives
timeout /t 3 >nul
set "AllOK=TRUE"
for %%L in (D E L) do (
if exist %%L:\ (
echo [OK] %%L: is accessible.
) else (
echo [WARNING] %%L: is not accessible. >&2
set "AllOK=FALSE"
)
)
if "!AllOK!"=="TRUE" (
echo.
echo [OK] Multi-partition layout complete:
echo D:\ Applications (100 GB^)
echo E:\ UserData (200 GB^)
echo L:\ Logs (remaining space^)
) else (
echo.
echo [WARNING] Some partitions may not have been created. Check Disk Management. >&2
)
endlocal
exit /b 0
Why separate partitions for server roles:
| Partition | Purpose | Benefit |
|---|---|---|
| D: Applications | Application binaries and configurations | Isolated from user data; easy to back up/restore independently |
| E: User Data | User files, databases, shared content | Can be sized and backed up based on growth patterns |
| L: Logs | Application and system log files | Prevents runaway logs from filling the data or app partitions |
Why Logs gets the remaining space:
Log files are the most unpredictable in size. By making the Logs partition the last one (using all remaining space), you ensure it has maximum room to grow. If logs fill this partition, applications on D: and user data on E: are unaffected.
The last partition uses create partition primary without size=:
When size= is omitted, DiskPart creates the partition using all remaining unallocated space. This is the standard pattern for the final partition in a multi-partition layout.
How to Avoid Common Errors
Problem: "No Usable Free Extent" Error
This means the disk has no unallocated space, all space is already assigned to existing partitions.
Solution: Delete an existing partition first, or select a different disk. To see existing partitions:
set "DPScript=%TEMP%\dp_listpart_%RANDOM%.txt"
(
echo select disk %DiskNum%
echo list partition
) > "%DPScript%"
diskpart /s "%DPScript%"
del "%DPScript%" 2>nul
Problem: MBR 4-Partition Limit
MBR disks allow a maximum of 4 primary partitions. If you already have 4, creating a 5th fails.
Solution: Convert the disk to GPT (which supports 128 partitions), or delete an unnecessary partition. If the disk must remain MBR, use extended/logical partitions for the 4th slot onward, though GPT is strongly preferred for modern systems.
Problem: Creating a Partition Without Formatting
If you create partition primary but skip format fs=ntfs quick, the new volume appears as "RAW" in Explorer. Windows displays a "You need to format this disk" dialog and the partition is unusable until formatted.
Solution: Always include format fs=ntfs label="..." quick immediately after creating the partition.
Problem: Partition Larger Than Available Space
If you specify size=512000 (500 GB) but the disk only has 300 GB unallocated, DiskPart fails with an error.
Solution: Check available space before creating (as shown in Method 1), or omit size= to use whatever space is available.
Wrong Way: Creating Partitions on Disk 0 Without Careful Planning
Disk 0 is typically the OS drive. Creating additional partitions on it can interfere with recovery partitions, EFI partitions, and Windows Update operations.
Correct Way: All methods in this guide refuse to operate on Disk 0 by default. Create data partitions on secondary disks (Disk 1, 2, etc.).
Best Practices and Rules
1. Size is in Megabytes
DiskPart's size= parameter uses megabytes. Use the reference table above to convert from GB to MB, or calculate: desired_GB × 1024 = size_MB.
2. Omit size= for the Last Partition
When creating multiple partitions, omit size= on the final one. DiskPart uses all remaining unallocated space, ensuring no space is wasted.
3. Always Format After Creating
An unformatted partition is "RAW" and unusable. Include format fs=ntfs label="..." quick after every create partition command.
4. Label Every Volume
Descriptive labels (e.g., "Applications", "UserData", "Logs") make volumes identifiable in Explorer, scripts, and Disk Management. Without labels, you have multiple volumes named "New Volume" that are indistinguishable.
5. Verify After Creation
After DiskPart completes, check if exist %Letter%:\ to confirm the partition is accessible. DiskPart may report success even if the format or letter assignment step failed internally.
6. Use GPT for New Disk Layouts
If you're initializing a disk as part of the partition creation (Method 3), always use convert gpt unless you have a specific requirement for MBR. GPT supports 128 partitions, disks larger than 2 TB, and provides a backup partition table for data protection.
Conclusions
Creating partitions with DiskPart via Batch script provides the precision needed for professional storage architecture. By automating partition creation with proper validation, disk existence checks, unallocated space verification, drive letter availability, and post-creation confirmation, you can set up complex multi-volume layouts reliably and repeatably. This automation is essential for provisioning servers, building consistent development environments, and managing large-scale hardware deployments.