If you still use a spinning hard drive for games, media or backups, Windows 11 includes a built-in defrag command that can analyse and optimise it. This guide follows Microsoft's official documentation for the command.
What defrag does
Microsoft Learn says the command "locates and consolidates fragmented files on local volumes to improve system performance". It applies to Windows 11 and Windows 10 as well as Windows Server, and you need to be a member of the local Administrators group, or equivalent, to run it.
Step 1: Open a terminal as administrator
Open Terminal, PowerShell or Command Prompt with administrator rights (run as administrator), because Microsoft says membership of the local Administrators group, or equivalent, is the minimum required to run the command.
Step 2: Analyse the drive first
To check a drive before optimising it, run defrag with the /a parameter, which Microsoft says "performs an analysis on the specified volumes". Add /v for verbose output with fragmentation statistics:
defrag D: /a /v
Replace D: with your hard drive's letter.
Step 3: Defragment the drive
Running defrag against a volume performs a traditional defrag, which Microsoft lists as the default. Add /u to see progress on screen and /v for verbose output:
defrag D: /u /v
By default the operation runs at low priority; Microsoft says /h runs it at normal priority instead. Other useful switches include /x for free space consolidation and /c to work on all volumes.
Let Windows pick the right job: /o
If you have a mix of hard drives and SSDs, the /o parameter "performs the proper optimization for each media type", so you don't have to work out which drive needs which treatment:
defrag /c /o
What about SSDs?
For SSDs the job is different. The defrag command's /l parameter "performs retrim on the specified volumes", which is the SSD-appropriate job. Our guide on how to optimise SSD TRIM in Windows 11 explains TRIM in more detail.
When defrag won't run
Microsoft lists volumes that can't be defragmented, including volumes locked by the file system, network drives, CD-ROMs and file systems other than NTFS, ReFS, FAT or FAT32. If the file system has marked a volume as dirty, which indicates possible corruption, Microsoft says you must run chkdsk before you can defragment it. You can check whether a volume is dirty with the fsutil dirty command. See how to check disk errors with chkdsk in Windows 11.