Skip to content

Instantly share code, notes, and snippets.

@auberginehill
Last active November 4, 2023 13:39
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save auberginehill/aa812bfa79fa19fbd880b97bdc22e2c1 to your computer and use it in GitHub Desktop.
Save auberginehill/aa812bfa79fa19fbd880b97bdc22e2c1 to your computer and use it in GitHub Desktop.
A Windows PowerShell script for disabling the automatic disk defragmentation.
<#
Disable-Defrag.ps1
#>
# Requires administrator rights
# Note: This script is mainly intended to use with systems with SSD drives, and is not particularly well suitable for systems with "traditional" HDD drives (with rotating disks).
# Note: The computer will be automatically rebooted at the end of this script (the first Step 5)
$path = $env:temp
$empty_line = ""
# Check if the PowerShell session is elevated (has been run as an administrator)
# Credit: alejandro5042: "How to run exe with/without elevated privileges from PowerShell" http://stackoverflow.com/questions/29266622/how-to-run-exe-with-without-elevated-privileges-from-powershell?rq=1
If (([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]"Administrator") -eq $false) {
$empty_line | Out-String
Write-Warning "It seems that this script is run in a 'normal' PowerShell window."
$empty_line | Out-String
Write-Verbose "Please consider running this script in an elevated (administrator-level) PowerShell window." -verbose
$empty_line | Out-String
$admin_text = "For performing system altering procedures, such as removing scheduled tasks, disabling services or writing the registry the elevated rights are mandatory. An elevated PowerShell session can, for example, be initiated by starting PowerShell with the 'run as an administrator' option."
Write-Output $admin_text
$empty_line | Out-String
"Exiting without making any changes to the system." | Out-String
Return ""
} Else {
$continue = $true
} # else
# Step 1
# Disable the scheduled run inside the Disk Defragmenter (DFRGUI) options
# Step 2
# Write the original Windows scheduled tasks to a CSV-file and remove the scheduled defragmentation task
<#
To disable the scheduled task:
Invoke-Expression 'SCHTASKS /Change /TN "Microsoft\Windows\Defrag\ScheduledDefrag" /Disable'
To create a custom scheduled task:
SCHTASKS /Create /TN "Microsoft\Windows\Defrag\ScheduledDefrag" /TR "'C:\Program Files (x86)\etc\test.exe'" /sc daily /st 00:00 /F
#>
$empty_line | Out-String
"Step 2: Writing the original Windows scheduled tasks to a CSV-file and removing the scheduled defragmentation task..." | Out-String
$tasks = SCHTASKS /Query /TN "Microsoft\Windows\" /FO csv | ConvertFrom-Csv -Header "TaskName","NextRunTime","Status" | Where-Object { $_.Status -ne "" } | sort TaskName
$tasks | Export-Csv "$path\scheduled_tasks.csv" -Delimiter ';' -NoTypeInformation -Encoding UTF8
$query = $tasks | Where-Object { $_.TaskName -like "*Microsoft\Windows\Defrag\ScheduledDefrag*" }
If ($query -eq $null) {
"Did not find the scheduled defragmentation task 'Microsoft\Windows\Defrag\ScheduledDefrag'."
} Else {
Invoke-Expression 'SCHTASKS /Delete /TN "Microsoft\Windows\Defrag\ScheduledDefrag" /F'
} # else
# Step 3
# Disable the Disk Defragmenter service via regedit
<#
To Start Disk Defragmenter: net start defragsvc
To Stop Disk Defragmenter: net stop defragsvc
To change Disk Defragmenter service Startup type:
Automatic: REG add "HKLM\SYSTEM\CurrentControlSet\services\defragsvc" /v Start /t REG_DWORD /d 2 /f
Automatic (Delayed Start): REG add "HKLM\SYSTEM\CurrentControlSet\services\defragsvc" /v Start /t REG_DWORD /d 2 /f
Manual: REG add "HKLM\SYSTEM\CurrentControlSet\services\defragsvc" /v Start /t REG_DWORD /d 3 /f
Disabled: REG add "HKLM\SYSTEM\CurrentControlSet\services\defragsvc" /v Start /t REG_DWORD /d 4 /f
Note: When the Startup type is changed to Automatic (Delayed Start) a new key DelayedAutostart is created with value 1.
REG add "HKLM\SYSTEM\CurrentControlSet\services\defragsvc" /v DelayedAutostart /t REG_DWORD /d 1 /f
When the Startup type is changed to Automatic from Automatic (Delayed Start), please manually change the DelayedAutostart value to 0.
REG add "HKLM\SYSTEM\CurrentControlSet\services\defragsvc" /v DelayedAutostart /t REG_DWORD /d 0 /f
Source: http://computerstepbystep.com/disk_defragmenter_service.html
#>
$empty_line | Out-String
"Step 3: Disabling the Disk Defragmenter service via regedit..." | Out-String
Invoke-Expression 'REG add "HKLM\SYSTEM\CurrentControlSet\services\defragsvc" /v Start /t REG_DWORD /d 4 /f'
# Step 4
# Edit the registry (add the following two registry keys to disable disk defragmentation feature and auto-layout)
# Note: Please see below (at the next Step 4) for furher information about these commands (REG add /?) and keys
$empty_line | Out-String
"Step 4: Adding two registry keys to disable the disk defragmentation feature and auto-layout..." | Out-String
Invoke-Expression 'REG add "HKLM\SOFTWARE\Microsoft\Dfrg\BootOptimizeFunction" /v Enable /t REG_SZ /d N /f'
Invoke-Expression 'REG add "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\OptimalLayout" /v EnableAutoLayout /t REG_DWORD /d 0 /f'
# Step 5
# Reboot the computer
# Credit: https://github.com/Disassembler0/Win10-Initial-Setup-Script
# Source: https://gist.github.com/alirobe/7f3b34ad89a159e6daa1
$empty_line | Out-String
Write-Host "Press any key to restart the computer..." -ForegroundColor Black -BackgroundColor White
$key = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
Write-Host "Restarting..."
Restart-Computer
<# Manually (Windows 7)
Step 1 Disable the scheduled run in the Disk Defragmenter options
1.A Click Start menu > All Programs > Accessories > System Tools > Disk Defragmenter
1.B At the bottom of Start menu in search box type DFRGUI and press [Enter].
1.C Click [Win-key] + R and type DFRGUI and press [Enter] or click OK.
2. On Disk Defragmenter box click on Configure schedule button and on the opened box uncheck Run on the schedule (recommended) checkbox.
3. Click on OK > Close
Step 2 Remove the scheduled defragmentation task
1.A Click Start menu > Control Panel > Administrative Tools > Task Scheduler
1.B At the bottom of Start menu in search box type taskschd.msc and press [Enter].
1.C Click [Win-key] + R and type taskschd.msc and press [Enter] or click OK.
2. Expand Microsoft > Windows > Defrag
3. In the right pane select the ScheduledDefrag and click on Delete
4. Close the Task Scheduler window
Step 3 Disable the Disk Defragmenter service
1.A Click Start menu > Control Panel > Administrative Tools > Services
1.B At the bottom of Start menu in search box type services.msc and press [Enter].
1.C Click [Win-key] + R and type services.msc and press [Enter] or click OK.
2. Find Disk Defragmenter (Enter D on your keyboard while another service is selected)
3. Double-click on Disk Defragmenter (or Right-click on Disk Defragmenter service and select Properties)
4. From the Startup type dropdown menu select Disabled
5. Click on Apply > OK and close the Services window
Step 4 Edit the registry (add the following two registry keys to disable disk defragmentation feature and auto-layout)
Source: https://msdn.microsoft.com/en-us/library/ms932871(v=winembedded.5).aspx
1. Backup the registry by for instance selecting File > Export after opening the regedit window.
2.A At the bottom of Start menu in search box type regedit and press [Enter].
2.B Click [Win-key] + R and type regedit and press [Enter] or click OK.
Key 1: Disable Background disk defragmentation
Key Name: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Dfrg\BootOptimizeFunction
Value Name: Enable
Type: REG_SZ
Value: N
Description: Accepted values for this entry are Y or N. If the entry is set to Y, Windows automatically optimizes the file location for boot optimization. This optimization occurs automatically if the system is idle for 10 minutes. Boot optimization improves startup time by locating startup files in contiguous clusters on the volume, reducing the movement of the disk head when reading the volume.
https://technet.microsoft.com/en-us/library/cc784391(v=ws.10).aspx
3. Expand the following path: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Dfrg\BootOptimizeFunction
4. Right-click on BootOptimizeFunction and select New > String and rename the newly created string (on the right-hand panel) as Enable
5. Make sure that the type of the Enable key is listed as REG_SZ (in the list at the right-hand panel)
6. Modify the value of "Enable" -key to N by double-clicking "Enable" (-key) and typing N and clicking OK
Key 2: Disable Background auto-layout
Key Name: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\OptimalLayout
Value Name: EnableAutoLayout
Type: REG_DWORD
Value: 0
Description: The auto-layout service moves the most-used data closer to the center of the disk to expedite boot time.
https://msdn.microsoft.com/en-us/library/ms932871(v=winembedded.5).aspx
7. Expand the following path: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\OptimalLayout
8. Right-click on OptimalLayout and select New > DWORD and rename the newly created DWORD (on the right-hand panel) as EnableAutoLayout
9. Make sure that the type of the EnableAutoLayout key is listed as REG_DWORD (in the list at the right-hand panel)
10. Modify the value of "EnableAutoLayout" -key to 0 by double-clicking "EnableAutoLayout" (-key) and typing 0 and clicking OK
11. Close the registry editor.
Step 5 Reboot the computer
#>
# Source: https://msdn.microsoft.com/en-us/library/ms932871(v=winembedded.5).aspx
# Source: https://social.technet.microsoft.com/Forums/windows/en-US/0b8f3115-da5f-4635-9b69-83fac6ff06ab/disable-automatic-disk-defragmentation?forum=w7itproinstall
# Source: http://computerstepbystep.com/disk_defragmenter_service.html
# Source: http://www.thewindowsclub.com/disable-defragmentation-ssd
# Source: http://windows7themes.net/en-us/disable-disk-defragmentation-windows-7-ssd/
# Source: https://github.com/Jackbennett/powershell/blob/master/Disable-DefragTask.ps1
# Source: https://github.com/Disassembler0/Win10-Initial-Setup-Script
# Source: https://gist.github.com/alirobe/7f3b34ad89a159e6daa1
# Source: http://stackoverflow.com/questions/29266622/how-to-run-exe-with-without-elevated-privileges-from-powershell?rq=1
@auberginehill
Copy link
Author

[reserved]

@dferens
Copy link

dferens commented Dec 22, 2020

Thank you, this is very helpful 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment