Skip to content

How to Script DiskPart Commands from a File in Batch Script

Learn how to automate DiskPart operations in Windows by writing commands to a text file and executing them via diskpart /s for repeatable disk management workflows.

DiskPart is a powerful Windows utility for managing disks, partitions, and volumes, but it operates in an interactive mode by default, requiring commands to be entered manually. To automate these operations in a batch script, you can place all required DiskPart commands into a plain text file and execute them using the /s switch. This method allows you to run complex disk configurations in a consistent and repeatable way without manual input.

This guide will teach you the standard and most reliable approach for automating DiskPart using script files. You'll learn how to generate temporary command files within a batch script, pass them to DiskPart for execution, and build reusable, auditable workflows for disk management tasks.

How DiskPart Script Files Work

┌──────────────────────┐         ┌──────────────────────┐
│  Batch Script (.bat) │         │  DiskPart Script     │
│                      │  writes │  (.txt)              │
│  (echo list disk     │ ──────► │  list disk           │
│   echo list volume   │         │  list volume         │
│  ) > script.txt      │         │                      │
│                      │         └──────────┬───────────┘
│  diskpart /s         │                    │
│    script.txt        │ ◄─ executes ───────┘
│                      │
│  del script.txt      │  (cleanup)
└──────────────────────┘
  1. The Batch script writes DiskPart commands to a text file.
  2. diskpart /s script.txt reads the file and executes each command in sequence.
  3. DiskPart returns control to the Batch script when all commands are processed.
  4. The Batch script cleans up the temporary file.

Method 1: Basic DiskPart Script Pattern

The foundation of all DiskPart automation: write commands to a temp file, execute, check the result, and clean up.

Implementation

@echo off
setlocal

:: Verify admin privileges
net session >nul 2>&1
if errorlevel 1 (
    echo [ERROR] DiskPart requires administrator privileges. >&2
    endlocal
    exit /b 1
)

set "DPScript=%TEMP%\dp_query_%RANDOM%.txt"

echo [ACTION] Querying disk and volume information...

:: Write DiskPart commands to the script file
(
    echo list disk
    echo list volume
) > "%DPScript%"

:: Execute the script
diskpart /s "%DPScript%"
set "DPResult=%errorlevel%"

:: Clean up the script file
del "%DPScript%" 2>nul

if %DPResult% neq 0 (
    echo [ERROR] DiskPart returned an error. >&2
    endlocal
    exit /b 1
)

echo [OK] Query complete.

endlocal
exit /b 0

Output:

[ACTION] Querying disk and volume information...

Microsoft DiskPart version 10.0.19041.3636

Copyright (C) Microsoft Corporation.
On computer: DESKTOP-HomePC

  Disk ###  Status         Size     Free     Dyn  Gpt
  --------  -------------  -------  -------  ---  ---
  Disk 0    Online           35 GB      0 B        *

  Volume ###  Ltr  Label        Fs     Type        Size     Status     Info
  ----------  ---  -----------  -----  ----------  -------  ---------  --------
  Volume 0     D   CCCOMA_X64F  UDF    DVD-ROM     5554 MB  Healthy
  Volume 1     C                NTFS   Partition     34 GB  Healthy    Boot
  Volume 2                      FAT32  Partition    200 MB  Healthy    System
[OK] Query complete.

Key elements of the pattern:

Element Purpose Example
%TEMP% directory Writable location for temporary scripts %TEMP%\dp_query.txt
%RANDOM% in filename Prevents collisions between concurrent runs dp_query_12847.txt
( ... ) > file Writes multiple commands in one operation Creates the DiskPart script
diskpart /s "file" Executes the script non-interactively Processes all commands sequentially
set "DPResult=%errorlevel%" Captures the exit code 0 = success, non-zero = error
del "%DPScript%" 2>nul Removes the temp file Cleanup even if DiskPart failed

Why %RANDOM% in the filename:

If two instances of the script run simultaneously (or if the script is called from a loop), a fixed filename like dp_query.txt would cause one instance to overwrite the other's commands. %RANDOM% generates a number between 0 and 32767, making collisions extremely unlikely.

Method 2: Parameterized DiskPart Scripts

Use Batch variables to make DiskPart scripts dynamic, the same script template can operate on different disks, letters, and labels based on parameters.

@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 Initializes a disk with GPT, creates one NTFS partition,
    echo and assigns the specified drive letter and label.
    echo.
    echo Example: %~nx0 1 E DataDrive
    endlocal
    exit /b 1
)

if "%Letter%"=="" set "Letter=E"
if "%Label%"=="" set "Label=Data"

net session >nul 2>&1
if errorlevel 1 (
    echo [ERROR] Administrator privileges required. >&2
    endlocal
    exit /b 1
)

:: Safety check
if "%DiskNum%"=="0" (
    echo [ERROR] Refusing to modify Disk 0 (OS drive^). >&2
    endlocal
    exit /b 1
)

if exist %Letter%:\ (
    echo [ERROR] Drive letter %Letter%: is already in use. >&2
    endlocal
    exit /b 1
)

echo [ACTION] Initializing Disk %DiskNum% as %Letter%: (%Label%^)...


<Aside type="danger" title="Destructive Operation">

The `clean` command in this script **permanently erases ALL data** on the selected disk. Verify the disk number carefully before proceeding.

</Aside>


set "DPScript=%TEMP%\dp_init_%RANDOM%.txt"

:: Build the script using variables
(
    echo rem DiskPart script generated by %~nx0
    echo rem Target: Disk %DiskNum% -^> %Letter%: (%Label%^)
    echo select disk %DiskNum%
    echo clean
    echo convert gpt
    echo create partition primary
    echo format fs=ntfs label="%Label%" quick
    echo assign letter=%Letter%
) > "%DPScript%"

:: Log the script contents before execution
echo [INFO] DiskPart commands:
type "%DPScript%"
echo.

:: Execute
diskpart /s "%DPScript%" >nul 2>&1
set "DPResult=%errorlevel%"

del "%DPScript%" 2>nul

if %DPResult% neq 0 (
    echo [ERROR] DiskPart initialization failed. >&2
    endlocal
    exit /b 1
)

:: Verify
timeout /t 2 >nul
if exist %Letter%:\ (
    echo [OK] Disk %DiskNum% initialized as %Letter%: (GPT, NTFS, "%Label%"^)
) else (
    echo [WARNING] DiskPart completed but %Letter%:\ is not accessible. >&2
)

endlocal
exit /b 0

Why parameterization matters:

Hardcoded DiskPart scripts work for one-time operations but cannot be reused. Parameterized scripts let you:

  • Initialize different disks without editing the script: init_disk.bat 1 E DataDrive
  • Run the same script across different servers with different disk layouts
  • Build higher-level workflows that call the script with computed parameters

Using rem in DiskPart scripts:

DiskPart supports rem (remark) comments. Adding a header with the script name, target, and timestamp makes the script self-documenting, useful when reviewing log files that include the script contents.

Method 3: Reusable Script Library

For environments where the same DiskPart operations are performed repeatedly, maintain a library of pre-written script files with a menu-driven launcher.

Directory structure:

C:\Scripts\DiskPart\
├── diskpart_menu.bat          (launcher)
├── scripts\
│   ├── list_disks.txt         (read-only queries)
│   ├── list_volumes.txt
│   ├── list_partitions_disk0.txt
│   └── README.txt             (documentation)
└── logs\
    └── diskpart_YYYYMMDD.log  (execution logs)

Library script files:

scripts\list_disks.txt:

rem List all physical disks
list disk

scripts\list_volumes.txt:

rem List all volumes with drive letters
list volume

Launcher script:

@echo off
setlocal

set "ScriptDir=%~dp0scripts"
set "LogDir=%~dp0logs"

net session >nul 2>&1
if errorlevel 1 (
    echo [ERROR] Administrator privileges required. >&2
    endlocal
    exit /b 1
)

if not exist "%LogDir%\" mkdir "%LogDir%"

:: Generate log filename
for /f "delims=" %%t in (
    'powershell -NoProfile -Command "Get-Date -Format ''yyyyMMdd_HHmmss''"'
) do set "LogFile=%LogDir%\diskpart_%COMPUTERNAME%_%%t.log"

echo ============================================================
echo   DISKPART SCRIPT LIBRARY
echo ============================================================
echo.
echo   Safe queries (read-only^):
echo     1. List all disks
echo     2. List all volumes
echo.
echo   Advanced operations (modify disk^):
echo     3. Custom script (provide filename^)
echo.
echo   0. Exit
echo.
echo ============================================================

set /p "Choice=Select an option: "

if "%Choice%"=="0" (
    endlocal
    exit /b 0
)

if "%Choice%"=="1" set "SelectedScript=%ScriptDir%\list_disks.txt"
if "%Choice%"=="2" set "SelectedScript=%ScriptDir%\list_volumes.txt"

if "%Choice%"=="3" (
    set /p "CustomScript=Enter script filename: "
    set "SelectedScript=%ScriptDir%\!CustomScript!"
)

if not defined SelectedScript (
    echo [ERROR] Invalid option. >&2
    endlocal
    exit /b 1
)

if not exist "%SelectedScript%" (
    echo [ERROR] Script file not found: %SelectedScript% >&2
    endlocal
    exit /b 1
)

echo.
echo [INFO] Executing: %SelectedScript%
echo [INFO] Output logged to: %LogFile%
echo.

:: Show the script contents first
echo --- Script Contents ---
type "%SelectedScript%"
echo --- End Script ---
echo.

:: Execute and log
(
    echo === DiskPart Execution Log ===
    echo Script: %SelectedScript%
    echo Date:   %date% %time%
    echo Computer: %COMPUTERNAME%
    echo User:   %USERNAME%
    echo.
    echo === Output ===
) > "%LogFile%"

diskpart /s "%SelectedScript%" >> "%LogFile%" 2>&1

:: Also display to screen
type "%LogFile%"

echo.
echo [OK] Execution complete. Log saved to: %LogFile%

endlocal
exit /b 0

Method 4: Capturing and Parsing DiskPart Output

DiskPart's output goes to stdout, which means you can redirect it to a log file or parse it in your Batch script.

Logging DiskPart Output

@echo off
setlocal

set "DPScript=%TEMP%\dp_query_%RANDOM%.txt"
set "DPOutput=%TEMP%\dp_output_%RANDOM%.txt"

net session >nul 2>&1
if errorlevel 1 (
    echo [ERROR] Administrator privileges required. >&2
    endlocal
    exit /b 1
)

(echo list disk) > "%DPScript%"

:: Redirect DiskPart output to a file
diskpart /s "%DPScript%" > "%DPOutput%" 2>&1

echo [INFO] DiskPart output:
echo.
type "%DPOutput%"

:: Parse the output for specific information
echo.
echo [INFO] Disk count:
find /c "Disk" "%DPOutput%" | findstr /r "[0-9]"

del "%DPScript%" 2>nul
del "%DPOutput%" 2>nul

endlocal
exit /b 0

Combining DiskPart Output with Batch Logic

@echo off
setlocal EnableDelayedExpansion

set "DPScript=%TEMP%\dp_list_%RANDOM%.txt"
set "DPOutput=%TEMP%\dp_result_%RANDOM%.txt"

net session >nul 2>&1
if errorlevel 1 (
    echo [ERROR] Administrator privileges required. >&2
    endlocal
    exit /b 1
)

(echo list volume) > "%DPScript%"
diskpart /s "%DPScript%" > "%DPOutput%" 2>&1

:: Count how many volumes exist
set "VolumeCount=0"
for /f "tokens=1-2" %%a in ('findstr /i "Volume" "%DPOutput%" ^| findstr /r "^..Volume"') do (
    set /a "VolumeCount+=1"
)

echo [INFO] Found !VolumeCount! volume(s^) on this system.

del "%DPScript%" 2>nul
del "%DPOutput%" 2>nul

endlocal
exit /b 0

How to Avoid Common Errors

Wrong Way: Running DiskPart Interactively in a Script

:: BROKEN: opens interactive DiskPart session, script hangs waiting for input
diskpart
list disk

Without /s, DiskPart starts an interactive session. The subsequent list disk line is interpreted as a Batch command (which doesn't exist), not a DiskPart command. The script either hangs or produces errors.

Correct Way: Always write commands to a file and use diskpart /s "file".

Problem: Script File Path Contains Spaces

:: MAY FAIL: unquoted path with spaces
diskpart /s C:\My Scripts\dp.txt

DiskPart interprets the space as the end of the filename, trying to open C:\My and treating Scripts\dp.txt as an unknown parameter.

Solution: Always wrap the script path in double quotes: diskpart /s "%ScriptFile%"

Problem: Script File Left Behind After Errors

If the Batch script crashes or is interrupted between creating the DiskPart script file and deleting it, the temp file persists.

Solution:

  • Use %TEMP% for temporary scripts (cleaned periodically by the system).
  • Use %RANDOM% in filenames to avoid collisions with stale files.
  • Place del immediately after diskpart /s, even before error checking.

Problem: Variable Expansion in Parenthesized Blocks

:: POTENTIAL ISSUE: if variables change inside the block
(
    echo select disk %DiskNum%
    echo format fs=ntfs label="%Label%" quick
) > script.txt

In a parenthesized ( ... ) block, all %var% references are expanded when the block is parsed, before any line executes. This is usually fine for DiskPart scripts since the variables are set before the block, but be aware that variables modified inside the same block won't be reflected.

Solution: For simple DiskPart script generation, standard %var% expansion works correctly as long as variables are set before the block. If you need to compute values inside the block, use EnableDelayedExpansion with !var!.

Problem: DiskPart Exit Codes Are Limited

DiskPart returns 0 for success and non-zero for errors, but it does not provide granular error codes. A "disk not found" error and a "permission denied" error may return the same non-zero code.

Solution: For critical operations, redirect DiskPart output to a file and parse for specific error messages:

diskpart /s "%DPScript%" > "%DPOutput%" 2>&1
findstr /i "error\|cannot\|denied\|not found" "%DPOutput%" >nul
if not errorlevel 1 (
    echo [ERROR] DiskPart reported errors. Check %DPOutput% for details. >&2
)

Best Practices and Rules

1. Always Use %TEMP% with %RANDOM% for Temporary Scripts

set "DPScript=%TEMP%\dp_operation_%RANDOM%.txt"

This prevents filename collisions and ensures the file is in a writable, periodically cleaned directory.

2. Always Clean Up Script Files

Delete the temporary script file immediately after DiskPart returns, even on error paths. DiskPart script files may contain sensitive information about your disk layout.

3. Always Check the Exit Code

diskpart /s "%DPScript%"
if errorlevel 1 (
    echo [ERROR] DiskPart failed. >&2
)

A non-zero exit code indicates failure. Never assume DiskPart succeeded without checking.

4. Log the Script Contents Before Execution

For auditing and debugging, display or log the DiskPart commands before executing them:

echo [INFO] DiskPart commands:
type "%DPScript%"

This creates an audit trail of exactly what was executed and is invaluable when debugging disk issues.

5. Add rem Comments to Script Files

DiskPart supports rem comments. Use them to document the purpose, target, and any safety notes:

rem Initialize Disk 1 as GPT with NTFS
rem Generated by init_disk.bat on 2024-05-10
select disk 1
clean
convert gpt

6. Use PowerShell for Data Extraction, DiskPart for Operations

DiskPart's text output is difficult to parse reliably. Use PowerShell's Get-Disk, Get-Partition, and Get-Volume for querying disk information, and DiskPart scripts only for operations that PowerShell cmdlets cannot perform (or for environments where PowerShell is unavailable).

7. Separate Read-Only Queries from Destructive Operations

Keep query scripts (list disk, list volume) separate from modification scripts (clean, format). Query scripts are safe to run anytime; modification scripts need confirmation, validation, and logging.

Conclusions

Scripting DiskPart commands from a file is the foundational technique behind all professional disk automation in Windows. By writing commands to a temporary file, executing with /s, checking the result, and cleaning up, you gain repeatability, auditability, and the ability to deploy complex storage configurations across your entire fleet. Combined with Batch parameterization for dynamic values and output redirection for logging, this pattern transforms DiskPart from an interactive tool into a powerful automation engine.

Navigation