-
-
#1
schtasks /Change /DISABLE /TN «\Microsoft\Windows\Defrag\ScheduledDefrag»
I use this command to disable the defragmentation schedule, it works, but the first time I restart after installing the system, the schedule turns on again. How to fix it?
-
-
#2
Try setting the task to disabled in the NTlite tasks page, so that it is in effect out of the box, rather than post-install. Also, here’s a related discussion on defrag, trim, and SSD (link).
Last edited:
-
-
#3
That’s the right command, but I tested if Windows changed the setting.
Post-Setup (Machine):
Code:
schtasks /Change /DISABLE /TN "\Microsoft\Windows\Defrag\ScheduledDefrag"
schtasks /query /TN "\Microsoft\Windows\Defrag\ScheduledDefrag" > C:\log1.txt
Post-Setup (User):
Code:
schtasks /query /TN "\Microsoft\Windows\Defrag\ScheduledDefrag" > C:\log2.txt
Code:
C:\>more log1.txt
Folder: \Microsoft\Windows\Defrag
TaskName Next Run Time Status
======================================== ====================== ===============
ScheduledDefrag N/A Disabled
C:\>more log2.txt
Folder: \Microsoft\Windows\Defrag
TaskName Next Run Time Status
======================================== ====================== ===============
ScheduledDefrag N/A Disabled
After first reboot: Disabled.
After installing Updates, and reboot: Disabled.
-
-
#4
That’s the right command, but I tested if Windows changed the setting.
Post-Setup (Machine):
Code:
schtasks /Change /DISABLE /TN "\Microsoft\Windows\Defrag\ScheduledDefrag" schtasks /query /TN "\Microsoft\Windows\Defrag\ScheduledDefrag" > C:\log1.txt
Post-Setup (User):
Code:
schtasks /query /TN "\Microsoft\Windows\Defrag\ScheduledDefrag" > C:\log2.txt
Code:
C:\>more log1.txt Folder: \Microsoft\Windows\Defrag TaskName Next Run Time Status ======================================== ====================== =============== ScheduledDefrag N/A Disabled C:\>more log2.txt Folder: \Microsoft\Windows\Defrag TaskName Next Run Time Status ======================================== ====================== =============== ScheduledDefrag N/A Disabled
After first reboot: Disabled.
After installing Updates, and reboot: Disabled.
Unfortunately, it doesn’t work for me.
-
-
#5
Did you try the three commands, from Post-Setup? If both logs say «Disabled», your problem is happening outside of NTLite.
-
-
#6
Did you try the three commands, from Post-Setup? If both logs say «Disabled», your problem is happening outside of NTLite.
I didn’t fully understand how to organize it all with log files. Why do you need 2 identical ones? Thank you in advance.
-
-
#7
1st log confirms that «schtasks /Disable» works as you requested, during Post-Setup (Machine).
2nd log confirms again the task is Disabled, during Post-Setup (User).
If both files report «Disabled», then whatever happened to re-enable the task wasn’t part of Post-Setup. This would suggest it was triggered by something else you later installed, or was pushed by Windows Update (?).
-
-
#8
1st log confirms that «schtasks /Disable» works as you requested, during Post-Setup (Machine).
2nd log confirms again the task is Disabled, during Post-Setup (User).If both files report «Disabled», then whatever happened to re-enable the task wasn’t part of Post-Setup. This would suggest it was triggered by something else you later installed, or was pushed by Windows Update (?).
And how to implement it correctly? Why exactly 2 different files with the same content?
-
-
#9
The point is basic troubleshooting: you run a command and immediately check if that command worked or not. Then we check again later if anything changed its setting. There are two opportunities to confirm, in Machine and User phases, by logging the /query to separate files.
If you don’t log the task’s state, then we can’t go back and understand what’s happening.
Machine commands:
schtasks | /Change /DISABLE /TN «\Microsoft\Windows\Defrag\ScheduledDefrag» |
schtasks | /query /TN «\Microsoft\Windows\Defrag\ScheduledDefrag» > C:\log_Machine.txt |
User commands:
schtasks | /query /TN «\Microsoft\Windows\Defrag\ScheduledDefrag» > C:\log_User.txt |
-
-
#10
The point is basic troubleshooting: you run a command and immediately check if that command worked or not. Then we check again later if anything changed its setting. There are two opportunities to confirm, in Machine and User phases, by logging the /query to separate files.
If you don’t log the task’s state, then we can’t go back and understand what’s happening.
Machine commands:
schtasks /Change /DISABLE /TN «\Microsoft\Windows\Defrag\ScheduledDefrag» schtasks /query /TN «\Microsoft\Windows\Defrag\ScheduledDefrag» > C:\log_Machine.txt User commands:
schtasks /query /TN «\Microsoft\Windows\Defrag\ScheduledDefrag» > C:\log_User.txt
Here is the result. I also noticed some nonsense with the language, although I did not touch the localization.
Вкл = On)
-
-
#11
I can’t read Russian (or Ukranian), and machine translation of this screen image doesn’t work. Does it say «Disabled»?
Your defrag Control Panel has no UAC icons next to each button. Why is that?
-
-
#12
I can’t read Russian (or Ukranian), and machine translation of this screen image doesn’t work. Does it say «Disabled»?
Your defrag Control Panel has no UAC icons next to each button. Why is that?View attachment 11281
There are no UAC icons since I have disabled it completely. It says that it is disabled. I also can’t figure out what’s wrong with the text in the log files, it’s not displayed correctly.
-
-
#13
You have some other problem. schtasks /query says «Disabled».
Defrag is not scheduled. This is from a clean W11 23H2 install.
-
-
#14
You have some other problem. schtasks /query says «Disabled».
View attachment 11282
Defrag is not scheduled. This is from a clean W11 23H2 install.
View attachment 11283
The console display is correct, but the status is «ready». The service starts only after the first reboot, it is initially disabled.
Below is a screenshot from the clean installation of the official image. There is also a problem with the display.
Last edited:
-
-
#15
Please attach your preset file (after removing any user passwords or license key).
<#
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
When it comes to defragmentation, the best recommendation I can make is to do something. The Windows scheduled task will be good enough for most situations, but for advanced configurations, you may want to leverage a more robust offering.
There is a ScheduledDefrag task that has its trigger inside set to disable by default. Is there a way through Powershell scripting to set that trigger to enable?
# Used by the RegisterTaskDefinition method
$TASK_CREATE_OR_UPDATE = 0x6
# Specify the computer name
$computerName = “localhost”
# Specify the task’s name
$taskName = “\Microsoft\Windows\Defrag\ScheduledDefrag”
$taskService = new-object -comobject “Schedule.Service”
$taskService.Connect($computerName)
$taskFolder = $taskService.GetFolder(“\”)
$registeredTask = $taskFolder.GetTask($taskName)
$registeredTask.Enabled = $TRUE
$taskDefinition = $registeredTask.Definition
$taskDefinition.Triggers | foreach-object { $_.Enabled = $TRUE }
[Void] $taskFolder.RegisterTaskDefinition($taskName, $taskDefinition,
$TASK_CREATE_OR_UPDATE, $NULL, $NULL, $taskDefinition.Principal.LogonType)
Other means:
If you don’t want to use the Windows scheduled task, the Disk Defragmenter tool, dfrgui.exe, is another way to set a defragmentation schedule. When you take this approach, the Windows scheduled task configuration (including the enabled/disabled trigger) will set to the new schedule
Other resources:
schtasks.exe – http://www.peetersonline.nl/index.php/powershell/managing-scheduled-tasks-remotely-using-powershell/ (PowerShell commands using schtasks.exe):
NB: you cannot use schtasks to modify the TRIGGER of the default defrag task. Prefer using powershell script with PowerShell Pack: http://archive.msdn.microsoft.com/PowerShellPack
To query the task : schtasks /query /s <computer> /TN \Microsoft\Windows\Defrag\ScheduledDefrag
To disable the task: schtasks /change /s <computer> /TN \Microsoft\Windows\Defrag\ScheduledDefrag /DISABLE
To update the execution time of that task : schtasks /change /s <computer> /TN \Microsoft\Windows\Defrag\ScheduledDefrag /ST 21:30 /ENABLE
To create a task using a XML file: schtasks /create /s <computer> /TN \Microsoft\Windows\Defrag\ScheduledDefrag /XML scheduledDefrag.xml
To delete a task (force): schtasks /delete /s <computer> /TN \Microsoft\Windows\Defrag\ScheduledDefrag /F
Other examples with schtasks: http://www.robvanderwoude.com/schtasks.php
Using PowerShell Pack: http://blog.powershell.no/2012/05/28/working-with-scheduled-tasks-from-windows-powershell/
IT Pro: 30 years experience for large companies — Technical manager and solution architect: Directory services and Identity Managemen expert, Password less solutions, FIDO2 specialist, Entra ID (formerly Azure AD), Microsoft 365, Azure infrastructures, Microsoft AD Security (ADDS, ADFS, ADCS), PowerShell, Quest solutions architect, Tenable.ad, PingCastle. Operating systems (Win/Lin). Unix and Microsoft interoperability. Data center Operations. Company integrations. Network architectures. Virtualization and storage infrastructures. HP/Dell servers deployments.
Multiple certifications: Azure, MCSE, MCPs, MCITS, ITIL, VCP, CCNA, CyberArk
View more posts
Время на прочтение7 мин
Количество просмотров40K
Автоматическая установка операционных систем семейства Windows требует от системного администратора тщательной проработки всех этапов выполнения. Давно интересуюсь данной темой, однако, в ходе многолетнего опыта по созданию собственных настроенных и обновлённых сборок Windows мной был упущен аспект работы с Планировщиком заданий. Разработчики Windows закладывают задачи, выполняемые в будущем по-расписанию, но ненужные и порой вредные «рядовому» пользователю. Список этих задач предлагаю к рассмотрению и обсуждению в данной статье.
Я уже писал здесь статьи про быструю и тонкую настройку операционной системы путём применения собранных мной твиков реестра, также была серия статей посвященных работе с образом Windows посредством DISM, где выкладывались мои скрипты: добавления пакетов обновлений, отключения компонентов, удаления «магазинных» приложений, получения информации из образа Windows. Скрипт приведённый в этой статье элементарный, основной интерес направлен на сам список задач, которые я предлагаю убрать из Планировщика заданий.
Скрипт
@echo off
schtasks /Delete /tn "\Microsoft\Windows\AppID\SmartScreenSpecific" /f &rem - 9 B
schtasks /Delete /tn "\Microsoft\Windows\Application Experience\AitAgent" /f &rem 7 9 -
schtasks /Delete /tn "\Microsoft\Windows\Application Experience\Microsoft Compatibility Appraiser" /f &rem 7 9 B
schtasks /Delete /tn "\Microsoft\Windows\Application Experience\ProgramDataUpdater" /f &rem 7 9 B
schtasks /Delete /tn "\Microsoft\Windows\Application Experience\StartupAppTask" /f &rem - 9 B
schtasks /Delete /tn "\Microsoft\Windows\ApplicationData\appuriverifierdaily" /f &rem - - B
schtasks /Delete /tn "\Microsoft\Windows\ApplicationData\appuriverifierinstall" /f &rem - - B
schtasks /Delete /tn "\Microsoft\Windows\Autochk\Proxy" /f &rem 7 9 B
schtasks /Delete /tn "\Microsoft\Windows\Customer Experience Improvement Program\BthSQM" /f &rem - 9 -
schtasks /Delete /tn "\Microsoft\Windows\Customer Experience Improvement Program\Consolidator" /f &rem 7 9 B
schtasks /Delete /tn "\Microsoft\Windows\Customer Experience Improvement Program\KernelCeipTask" /f &rem 7 9 B
schtasks /Delete /tn "\Microsoft\Windows\Customer Experience Improvement Program\UsbCeip" /f &rem 7 9 B
schtasks /Delete /tn "\Microsoft\Windows\Defrag\ScheduledDefrag" /f &rem 7 9 B
schtasks /Delete /tn "\Microsoft\Windows\Device Information\Device" /f &rem - - B
schtasks /Delete /tn "\Microsoft\Windows\Diagnosis\Scheduled" /f &rem 7 9 B
schtasks /Delete /tn "\Microsoft\Windows\DiskDiagnostic\Microsoft-Windows-DiskDiagnosticDataCollector" /f &rem 7 9 B
schtasks /Delete /tn "\Microsoft\Windows\LanguageComponentsInstaller\Installation" /f &rem - - B
schtasks /Delete /tn "\Microsoft\Windows\LanguageComponentsInstaller\Uninstallation" /f &rem - - B
schtasks /Delete /tn "\Microsoft\Windows\Maintenance\WinSAT" /f &rem 7 9 B
schtasks /Delete /tn "\Microsoft\Windows\Maps\MapsToastTask" /f &rem - - B
schtasks /Delete /tn "\Microsoft\Windows\Maps\MapsUpdateTask" /f &rem - - B
schtasks /Delete /tn "\Microsoft\Windows\Mobile Broadband Accounts\MNO Metadata Parser" /f &rem - 9 B
schtasks /Delete /tn "\Microsoft\Windows\MobilePC\HotStart" /f &rem 7 - -
schtasks /Delete /tn "\Microsoft\Windows\MUI\LPRemove" /f &rem 7 9 B
schtasks /Delete /tn "\Microsoft\Windows\NetTrace\GatherNetworkInfo" /f &rem 7 9 B
schtasks /Delete /tn "\Microsoft\Windows\Power Efficiency Diagnostics\AnalyzeSystem" /f &rem 7 9 B
schtasks /Delete /tn "\Microsoft\Windows\RAC\RacTask" /f &rem 7 9 -
schtasks /Delete /tn "\Microsoft\Windows\RemoteAssistance\RemoteAssistanceTask" /f &rem 7 9 B
schtasks /Delete /tn "\Microsoft\Windows\RetailDemo\CleanupOfflineContent" /f &rem - - B
schtasks /Delete /tn "\Microsoft\Windows\SettingSync\BackgroundUploadTask" /f &rem - 9 B
schtasks /Delete /tn "\Microsoft\Windows\SettingSync\BackupTask" /f &rem - 9 B
schtasks /Delete /tn "\Microsoft\Windows\SettingSync\NetworkStateChangeTask" /f &rem - 9 B
schtasks /Delete /tn "\Microsoft\Windows\Setup\EOSNotify" /f &rem 7 9 -
schtasks /Delete /tn "\Microsoft\Windows\Setup\EOSNotify2" /f &rem 7 9 -
schtasks /Delete /tn "\Microsoft\Windows\Setup\SetupCleanupTask" /f &rem - 9 B
schtasks /Delete /tn "\Microsoft\Windows\Speech\SpeechModelDownloadTask" /f &rem - - B
schtasks /Delete /tn "\Microsoft\Windows\SystemRestore\SR" /f &rem 7 9 B
schtasks /Delete /tn "\Microsoft\Windows\Time Synchronization\SynchronizeTime" /f &rem 7 9 B
schtasks /Delete /tn "\Microsoft\Windows\Windows Error Reporting\QueueReporting" /f &rem 7 9 B
schtasks /Delete /tn "\Microsoft\Windows\WindowsBackup\ConfigNotification" /f &rem 7 - -
schtasks /Delete /tn "\Microsoft\Windows\WS\License Validation" /f &rem - 9 -
schtasks /Delete /tn "\Microsoft\Windows\WS\WSRefreshBannedAppsListTask" /f &rem - 9 -
schtasks /Delete /tn "\Microsoft\XblGameSave\XblGameSaveTask" /f &rem - - B
schtasks /Delete /tn "\Microsoft\XblGameSave\XblGameSaveTaskLogon" /f &rem - - B
timeout 3 > nul
Использование
Запуск под учётной записью администратора приводит к выполнению последовательности команд schtasks с аргументом /Delete (удалить) последующее имя задачи за аргументом /tn. Ключ /f подавляет вывод уведомлений о подтверждении. Достаточно одного выполнения скрипта, а повторные запуски лишь отобразят список ошибок из-за невозможности удалить то, чего уже нет. Скрипт не наделён «интерактивностью», так как используется в процессе автоматической установки Windows.
Применимость
Список задач, подлежащих удалению данным скриптом, составлен для следующих версий ОС: Windows 7 Professional VL SP1 (updated Jan 2020 — End of Support), Windows 8.1 Professional VL Update3 (updated Jan 2023 — End of Support), Windows 10 v1607 Enterprise LTSB (updated Jan 2023). Изначально хотел написать отдельные скрипты для каждой версии Windows, но увидел, что список задач значительно повторяется и поэтому объединил в один. В планах добавить в список ненужные задачи из следующих версий ОС: Windows 10 v1809 Enterprise LTSC, Windows 10 v21H2 Professional BE (business editions) — на базе которых также делаю свои сборки.
Комментирование
Чтобы не запутаться в списке задач — откуда каждая из них взялась и стоит ли её удалять — в комментарии, в конце строки каждой команды можно видеть подсказку в каких версиях Windows удаляемая задача встречается. Это удобно для анализа и редактирования списка. Также присутствует алфавитная сортировка задач, с группировкой разделов по первой букве. Взгляните, в Windows 7 ненужных задач было не много — всего 22, в Windows 8.1 их уже стало 30, в Windows 10 LTSB уже 41! Страшно представить сколько «мусора» в Планировщике заданий я обнаружу в версии Windows 10 Enterprise LTSC и особенно в Windows 10 21H2.
Откуда список
Я составлял данный список путём вдумчивого чтения описания каждой задачи и анализа параметров её запуска. За дополнительной информацией обращался к источникам в Интернете, в том числе англоязычным, в том числе официальным. Не всегда мне удавалось найти однозначный ответ на вопрос: «стоит удалять данную задачу или нет?». Бывало так, что описание у задачи отсутствовало, параметры запуска скрыты, триггеры срабатывания отсутствуют, но при этом задача почему-то выполнялась. В сети Интернет не нашел аналогичного списка с развёрнутой дискуссией обсуждения целесообразности включения в него тех или иных задач.
Удаление или отключение?
Консольная команда schtasks имеет полный набор аргументов для управления Планировщиком заданий Windows. В ходе поиска информации по отдельным задачам в сети Интернет мне попадались скрипты других авторов, где ненужные задачи отключались (подаргумент /disable аргумента /Change). Я использую более радикальный подход — просто удаляю (аргумент /Delete) ненужные мне задачи. Ведь вариант «отключение» подразумевает что мне когда-нибудь понадобится включить некоторую задачу. Не представляю себе ситуацию, когда мне понадобится снова включить, например, уведомление об окончании срока поддержки или телеметрию. Что скажете?
Вердикт на удаление
Какие задачи в Планировщике заданий принимать к рассмотрению? Рассмотрим какие задачи бывают, в каком состоянии и насколько открыты. На начальном этапе были мысли написать простой скрипт, который бы удалял вообще все задачи (без разбора), но данный подход опасен тем, что может привести к снижению производительности и надёжности системы, так что пришлось разбираться. Итак:
- Состояние — Отключено
Я не включал в список на удаление задачи в состоянии «Отключено». Как правило это либо «артефакты» прошлых версий Windows, либо уже отключенные самими разработчиками посредством пакетов обновлений, либо ещё что… - Бесполезное обслуживание
Это пример задач которые запускают ежедневное/еженедельное выполнение различных служб в назначенное время, как правило ночью. Как итог, эти задачи не выполняются так как ночью мой компьютер («рядового» пользователя) отключён. Также мне не надо чтобы днём отвлекались ресурсы моего компьютера. - Телеметрия
Это страшное слово знакомо многим системным администраторам и не только. Значительная часть удаляемых по моему списку задач относится к средствам телеметрии и слежения за пользователем со стороны компании Майкрософт. Мой компьютер — это МОЙ КОМПЬЮТЕР! - «Тёмные лошадки»
Самая сложная категория задач. Как правило, много их появилось в версии Windows 10. Отличительные особенности: описание размыто или отсутствует, параметры запуска скрыты, триггеры срабатывания отсутствуют, но при этом задача каким-то чудом регулярно запускается, о чём указано в поле «Время прошлого запуска».
Обсуждение
Конечно, представленный мной список может быть не полным или наоборот избыточным. Есть вероятность, что я не распознал в какой-то задаче «скрытого пожирателя ресурсов» или наоборот включил в список задачу удаление которой скорее навредит работоспособности ОС. Прошу аргументированно высказывать своё мнение, делится опытом. В данном ключе обсуждение может начинаться по двум сценариям:
- Вы включили в список задачу «X», удаление которой приведёт к следующим негативным последствиям…
- Вы не включили в список задачу «Y», которая является вредной, так как выполняет следующие действия…
Список составлен для компьютера предназначенного для домашнего использования. Прошу к рассмотрению и обсуждению!
By default on Windows 7, Scheduled task for Defragmenting local HDDs is enabled to run Every Wednesday at 01:00 AM.
You can disable this task using following command:
schtasks /change /tn «microsoft\windows\defrag\ScheduledDefrag» /disable
If you want to disable ScheduledDefrag to the Domain computers in your company then create a BAT file and include it as computer based GPO logon script.
After applying this GPO to the target computer run taskschd.msc. The status of ScheduledDefrag is disabled.