279 lines
19 KiB
Markdown
279 lines
19 KiB
Markdown
# System cleanup
|
|
|
|
`Start-SystemCleanup.ps1` combines the operations of `Cleanup-SystemTempFiles.ps1`
|
|
and `Start-Cleanup.ps1`, with additional cache and diagnostic targets. The old
|
|
scripts remain unchanged. Upload `rmm/Start-SystemCleanup.ps1` to the RMM and run
|
|
as SYSTEM under **64-bit Windows PowerShell 5.1**. No reboot is initiated.
|
|
On 64-bit Windows the core rejects a 32-bit host before changes.
|
|
|
|
## First run and configuration
|
|
|
|
Define the script variables in Syncro using the names below **without `$`**.
|
|
Use Dropdown variables with `true` and `false` choices for boolean options, and
|
|
a single-selection Dropdown for `CleanupDiskCleanupItems` with the five presets
|
|
below. Select `Standard` for the usual Disk Cleanup behavior. The three day counts
|
|
can be Runtime variables, requiring a nonempty number each run; omit those variable
|
|
definitions if you want the core's defaults instead. Syncro supplies all values as
|
|
strings. Uploading the shim does not create these variable definitions in Syncro.
|
|
|
|
Remove the former `CleanupDiskCleanup` variable from Syncro and any manual callers.
|
|
`CleanupDiskCleanupItems=None` is now the only operator setting to disable native
|
|
Disk Cleanup. A caller still supplying the removed boolean fails before cleanup,
|
|
with migration instructions, so an old `false` value cannot be silently ignored.
|
|
|
|
Like `rmm/Install-MicrosoftOffice365.ps1`, the shim documents the variables but
|
|
does not assign them. It loads Tools.ps1 and calls
|
|
`Run-Script -LivePSScript Start-SystemCleanup`, preserving Syncro's injected
|
|
variables through the dot-sourced caller scope; do not add `-Arguments`. The core
|
|
parses these strings and supplies defaults for absent variables, including direct
|
|
use. The core does not need to download Tools.ps1 itself.
|
|
|
|
Run once with `CleanupReportOnly=true`, then set it to `false` to apply. Report
|
|
mode assesses **all categories regardless of their enablement**, using the current
|
|
retention settings. It leaves the enablement variables unchanged. The compact
|
|
report starts with the unique enabled savings and additional disabled savings,
|
|
followed by a component-store note, then every category once in three sections:
|
|
|
|
- **Enabled:** eligible for cleanup on an apply run, subject to the reported conditions.
|
|
- **Disabled:** potential savings only; these categories will not run during apply
|
|
unless you enable their corresponding `Cleanup*` variables.
|
|
- **Blocked on server:** listed for visibility, without scanning or executing their
|
|
actions. These cannot be enabled on a server.
|
|
|
|
For example, `CleanupDownloadedExecutables=false` still reports old downloaded
|
|
executables in the Disabled section on a client. With `CleanupReportOnly=false`,
|
|
that category is skipped entirely until explicitly enabled.
|
|
|
|
File categories report their independent eligible file counts and logical bytes.
|
|
These category estimates can overlap (for example, a duplicate downloaded EXE).
|
|
The enabled total counts each file path once. The disabled total shows additional
|
|
unique file bytes beyond those already counted in enabled categories. Native
|
|
operations such as Disk Cleanup, Search compaction, Delivery Optimization,
|
|
and component cleanup show `-` and **not estimated**, not
|
|
zero. Disk Cleanup shows its preset (or Custom) and selected handler count.
|
|
`None` places Disk Cleanup in the Disabled section. Servers always place it in
|
|
the Blocked section, regardless of the preset.
|
|
Skipped/unavailable categories say **not assessed**; failed or partially assessed
|
|
categories are labeled incomplete. In-use application checks remain enforced, so
|
|
close those applications and rerun to obtain their estimates. Unknown savings are
|
|
excluded from the totals, and file sizes do not guarantee physical space savings.
|
|
|
|
The report-only diagnostics run regardless of the corresponding cleanup flags:
|
|
|
|
- **DisableHibernation:** the category's MiB column shows the current system-drive
|
|
`hiberfil.sys` size, or `0.00` when absent. Its note identifies this as file size.
|
|
- **ShadowCopies:** the category's MiB column shows used shadow storage for the
|
|
system volume, or `0.00` when no storage association exists. Its note identifies
|
|
VSS usage and the drive where the data resides. Storage on another drive is
|
|
labeled accordingly; it does not represent space occupied on C:. Allocation
|
|
details remain available in verbose output.
|
|
- **ComponentStore:** a short note that removing superseded updates may free
|
|
substantial space, or little/none. The component store is not analyzed, and no
|
|
Yes/No recommendation or package count is calculated. The note appears even if
|
|
`CleanupComponentStore=false` or `CleanupDiskCleanupItems=None`.
|
|
|
|
There are no separate Hibernation or ShadowStorage diagnostic lines. The two
|
|
native rows keep `-` in the Files column. Failed/unsupported inspections show `-`
|
|
for MiB and **unavailable**, never zero. Structured results expose these usage
|
|
measurements as `UsageBytes`, separately from `CandidateBytes`.
|
|
|
|
These are **current usage and potential, not extra reclaimable bytes**;
|
|
they are excluded from both savings totals. VSS data may be shared between
|
|
snapshots, and the script retains the newest snapshot. Hibernation/VSS diagnostics
|
|
remain unassessed on servers under the existing server policy. The component-store
|
|
note appears on both clients and servers. Diagnostics are skipped in
|
|
apply mode and require no new Syncro variables.
|
|
|
|
Report mode does not launch DISM analysis, avoiding its additional runtime on slow
|
|
endpoints. Component cleanup removes superseded updates, so potential savings
|
|
depend on accumulated updates and previous Windows maintenance. A large WinSxS
|
|
folder alone does not indicate how much is reclaimable. Actual cleanup still uses
|
|
the existing background task when `CleanupComponentStore=true` in apply mode.
|
|
|
|
The default output is designed for Syncro's limited script output: one line per
|
|
category, including zero results, without a second PowerShell object dump or
|
|
per-category progress chatter. Column sizes are in MiB; positive sizes below
|
|
0.01 MiB display as `<0.01`. The group identifies whether a category is enabled;
|
|
its variable is `Cleanup<Category>`, except Disk Cleanup uses
|
|
`CleanupDiskCleanupItems`. Skip, failure, and partial-assessment reasons remain
|
|
visible. Long diagnostic notes are shortened to one line.
|
|
|
|
To troubleshoot, set `$VerbosePreference = 'Continue'` in the caller before
|
|
`Run-Script`. Verbose output includes progress, full diagnostic notes, and the
|
|
selected/unselected Disk Cleanup handler lists; it can exceed Syncro's output
|
|
limit, so use a local PowerShell capture when full detail is needed. No additional
|
|
Syncro variable is required. The `Invoke-SystemCleanup` function still returns
|
|
structured results for programmatic callers; the script entry suppresses their
|
|
automatic formatting after printing the human-readable report.
|
|
|
|
Report mode performs no cleanup, changes no cleanup registry settings, stops no
|
|
services, launches no native programs, and requests no scheduled maintenance.
|
|
Acquiring a named mutex prevents overlapping
|
|
runs; the RMM bootstrap still downloads Tools/core and may produce its usual logs.
|
|
Native cleanup savings cannot be estimated from these usage measurements alone.
|
|
|
|
Boolean options accept native booleans or true/false, yes/no, 1/0 strings. Blank
|
|
or unrecognized boolean values fail before cleanup. Retention values must be
|
|
whole days from 1 through 3650. Unknown Disk Cleanup presets/handler names, blank
|
|
selections, and mixtures of presets with other values also fail before cleanup.
|
|
|
|
| Variable | Default | Purpose |
|
|
| --- | --- | --- |
|
|
| `CleanupReportOnly` | true | Assess all categories versus apply enabled categories only |
|
|
| `CleanupTempDays` | 7 | Temp files, installers, browser cache, Apple downloads |
|
|
| `CleanupDiagnosticDays` | 30 | CBS, WER archives, dumps, Revit journals |
|
|
| `CleanupBackupDays` | 30 | Downloads, backups, time spent in Recycle Bin |
|
|
| `CleanupSystemTemp` | true | Windows Temp, including EVTX, misc logs, AppxErrorReport, Chocolatey |
|
|
| `CleanupUserTemp` | true | Registered user profiles' Local Temp; AutoCAD `.ac$` only with AutoCAD closed |
|
|
| `CleanupServiceTemp` | true | LocalService, NetworkService, SYSTEM profile temp folders |
|
|
| `CleanupCBSArchives` | true | `CbsPersist_*.log` and `CbsPersist_*.cab` |
|
|
| `CleanupActiveCBSLog` | false | Old CBS.log, only with TrustedInstaller already stopped and archives >=200 MiB |
|
|
| `CleanupCrashDumps` | true | MEMORY.DMP, Minidump, LiveKernelReports including PDCRevocation, Genetec Dumps, user/service CrashDumps and temp `.dmp` |
|
|
| `CleanupWERArchives` | true | System/user/service WER ReportArchive; queues retained |
|
|
| `CleanupAutodeskInstallers` | false | Old extracted directories under system drive Autodesk, excluding WI |
|
|
| `CleanupRecycleBin` | false | System-drive recycle items, using deletion date from `$I` metadata |
|
|
| `CleanupDisableHibernation` | false | `powercfg /hibernate off` |
|
|
| `CleanupCompactSearch` | false | Compact Windows.edb with esentutl; temporarily stop WSearch |
|
|
| `CleanupShadowCopies` | false | Delete all but newest system-volume shadow copy |
|
|
| `CleanupDownloadedExecutables` | false | Old `.exe` files in each profile's Downloads |
|
|
| `CleanupDuplicateDownloads` | false | Old `name (number).ext` files with a matching original and SHA-256 |
|
|
| `CleanupOutlookBackups` | false | Old Outlook `.bak` files, with Outlook closed |
|
|
| `CleanupITunesBackups` | false | Old complete MobileSync backup directories, with Apple apps closed |
|
|
| `CleanupAppleDownloads` | false | Old IPSW/IPA files from the previously commented-out iTunes block |
|
|
| `CleanupBrowserCache` | false | Chrome/Edge Cache, Code Cache, GPUCache in Default/Profile N, with that browser closed |
|
|
| `CleanupRevitJournals` | true | Old journal*.txt only, with Revit closed |
|
|
| `CleanupDeliveryOptimization` | false | Supported cache cmdlet, retaining pinned content |
|
|
| `CleanupComponentStore` | false | Request Windows StartComponentCleanup scheduled task; asynchronous |
|
|
| `CleanupDiskCleanupItems` | Standard | Disk Cleanup preset; None disables it; clients only. Exact handler lists/arrays also accepted |
|
|
|
|
## Disk Cleanup presets
|
|
|
|
Configure these exact dropdown choices for `CleanupDiskCleanupItems`:
|
|
|
|
| Preset | Selected handlers |
|
|
| --- | --- |
|
|
| `Standard` (default) | Downloaded Program Files; Internet Cache Files; Thumbnail Cache; Active Setup Temp Folders; Temporary Setup Files; Windows Defender; RetailDemo Offline Content |
|
|
| `StandardAndUpdates` | All Standard handlers, plus Service Pack Cleanup; Update Cleanup; Upgrade Discarded Files; Windows Upgrade Log Files |
|
|
| `StandardUpdatesAndDiagnostics` | All StandardAndUpdates handlers, plus Memory Dump Files; Old ChkDsk Files; System error memory dump files; System error minidump files; Setup Log Files; Windows Error Reporting Archive Files; Windows Error Reporting Queue Files; Windows Error Reporting System Archive Files; Windows Error Reporting System Queue Files; Windows Error Reporting Temp Files |
|
|
| `All` | All 35 supported legacy handlers listed below, including Recycle Bin, user file versions, previous installations, and Windows ESD installation files |
|
|
| `None` | No handlers; native Disk Cleanup does not run |
|
|
|
|
Presets are cumulative and case-insensitive; surrounding whitespace is ignored.
|
|
`Standard` preserves the previous default selection. `All` selects the explicit
|
|
supported list, not arbitrary additional handlers installed on an endpoint.
|
|
No preset changes other `Cleanup*` flags or bypasses the server exclusion.
|
|
|
|
Exact comma-separated handler names and arrays remain supported for manual or
|
|
existing callers, for example `Thumbnail Cache,Internet Cache Files`. They are
|
|
reported as a custom selection. Use one preset or a list of exact handlers; do
|
|
not mix them. A supplied blank/null value is invalid; an absent variable defaults
|
|
to `Standard`. Use the nonempty value `None` to disable native Disk Cleanup.
|
|
|
|
## Server policy
|
|
|
|
`Win32_OperatingSystem.ProductType` identifies clients (1), domain controllers
|
|
(2), and other servers (3). Both server types are blocked from these categories,
|
|
even if enabled or selected by a Disk Cleanup preset:
|
|
|
|
- ShadowCopies
|
|
- DisableHibernation
|
|
- CompactSearch
|
|
- DownloadedExecutables and DuplicateDownloads
|
|
- OutlookBackups and ITunesBackups
|
|
- DiskCleanup (every handler, including any newly selected items)
|
|
|
|
Unknown or failed OS identification stops the run before changes. There is no
|
|
override. Disk Cleanup availability varies by Server version/installation; the
|
|
OS gate is enforced even if cleanmgr.exe exists. Native and file categories
|
|
outside this list can run on both clients and servers when enabled.
|
|
|
|
## All legacy Disk Cleanup operations
|
|
|
|
Every handler from Start-Cleanup.ps1 remains selectable, including those that
|
|
were disabled there. The old groups are listed here for migration; select a
|
|
preset above or exact handler names in `CleanupDiskCleanupItems`. The old group
|
|
names themselves are not accepted as presets.
|
|
|
|
| Old group | Handler names |
|
|
| --- | --- |
|
|
| User | Downloaded Program Files; Internet Cache Files; Offline Pages Files; Recycle Bin; Temporary Files; Thumbnail Cache; User file versions |
|
|
| System | Active Setup Temp Folders; BranchCache; Memory Dump Files; Old ChkDsk Files; RetailDemo Offline Content; Temporary Files; System error memory dump files; System error minidump files; Temporary Setup Files; Windows Defender; Windows Error Reporting Archive Files; Windows Error Reporting Queue Files; Windows Error Reporting System Archive Files; Windows Error Reporting System Queue Files; Windows Error Reporting Temp Files |
|
|
| WindowsUpdate | Service Pack Cleanup; Update Cleanup; Upgrade Discarded Files; Windows Upgrade Log Files |
|
|
| WindowsPreviousVersions | Previous Installations; Setup Log Files |
|
|
| Invasive | Windows ESD installation files |
|
|
| Misc | Content Indexer Cleaner; Delivery Optimization Files; Device Driver Packages; GameNewsFiles; GameStatisticsFiles; GameUpdateFiles; Temporary Sync Files |
|
|
|
|
Selecting a handler explicitly permits Windows to apply that handler's own
|
|
retention rules. The script's day settings **do not apply to cleanmgr**. For
|
|
example, its Recycle Bin/dump/WER handlers can remove recent data; its previous
|
|
installation/service pack/ESD handlers can remove rollback or recovery options.
|
|
`/sagerun` enumerates drives; it is not restricted to the system drive. The
|
|
default selection omits those recovery and diagnostic handlers.
|
|
|
|
Instead of persistent sageset flags or legacy NoSettings/NoCleaning/DeleteSettings
|
|
modes, each live run allocates an unused settings slot across all registered
|
|
handlers, writes only selected handlers, waits for cleanmgr, then removes its own
|
|
temporary flags in finally. Existing settings are preserved. Abnormal process
|
|
termination can leave a temporary slot behind; future runs skip occupied slots.
|
|
|
|
## Deletion and operational boundaries
|
|
|
|
- Inspect each file's modification time; an old parent never authorizes deletion
|
|
of newer children. Ordinary cache/temp directories are retained.
|
|
- Use literal local paths, verify containment, and skip reparse points and linked
|
|
ancestors (including OneDrive placeholders). UNC paths and redirected profile
|
|
folders reached through links are skipped. No ownership or ACL changes.
|
|
- Skip in-use files. A category inventory failure is reported and later categories
|
|
continue; the run fails at the end if a category/maintenance operation failed.
|
|
- Generic temp cleanup excludes `.dmp`, `.ac$`, and AutoCAD `.sv$` autosaves.
|
|
Dumps get diagnostic retention; `.ac$` gets a separate closed-app check;
|
|
`.sv$` is retained. Revit model/recovery files and browser site storage are
|
|
outside the dedicated cache/journal targets.
|
|
- Backup/installer directories are inspected as complete units. Recent content
|
|
or links retain the unit, and apply mode probes for in-use files before deleting
|
|
any part of a unit. No recursive Remove-Item is used. Failed file deletion
|
|
retains the remaining directory; there is no transaction or rollback.
|
|
- Recycle Bin cleanup uses `$I` FILETIME metadata and removes the paired `$R`
|
|
content before its metadata. Unsupported/corrupt metadata is retained.
|
|
- Downloads are not discovered via redirected Known Folders. Duplicate matching
|
|
requires extension, size, and SHA-256 equality. Read handles prevent concurrent
|
|
writes during hashing/deletion; filesystem activity outside the script can still
|
|
rename or delete files, so this remains an opt-in operation.
|
|
- Active CBS cleanup never stops TrustedInstaller. Search compaction preserves
|
|
service startup settings, requires free space for a temporary database, and
|
|
restarts WSearch in finally only if it was originally running. An interrupted
|
|
native compaction can leave its uniquely named temporary database for inspection.
|
|
- VSS deletion uses exact inventoried snapshot IDs and preserves the newest;
|
|
native failures stop that category. Backup-managed snapshots may refuse deletion.
|
|
- Component cleanup uses Windows' scheduled task, with no ResetBase or direct
|
|
WinSxS deletion. Task submission is reported separately from completion.
|
|
- Native operations report exit codes and use hidden windows. No hard execution
|
|
timeout is imposed; allow adequate RMM runtime if enabling maintenance work.
|
|
- Byte counters are file lengths, not guaranteed physical disk savings (compression,
|
|
sparse files, hard links, and native cleanup affect actual reclaimed space).
|
|
|
|
## Validation
|
|
|
|
Run `powershell.exe -NoProfile -File tests/Start-SystemCleanup.Tests.ps1`.
|
|
Tests load function definitions via the AST, use disposable fixture directories,
|
|
and mock OS, registry, native processes, and service operations. They do not run
|
|
cleanup against the host's Windows folders or invoke maintenance programs.
|
|
Coverage includes disabled-category estimates, separate report groups, unique
|
|
totals for overlapping categories, and disabled categories remaining untouched in
|
|
apply mode. Preset tests verify exact handler membership, cumulative selections,
|
|
RMM scope preservation, None disabling native work, and the server exclusions.
|
|
Output tests cover the duplicate-object regression, a 22-category preview under
|
|
4 KiB including diagnostics, separate enabled/disabled sections, and preservation
|
|
of diagnostic notes. Regression checks ensure DISM analysis is absent and report
|
|
diagnostics launch no native programs.
|
|
Hibernation/VSS tests cover usage in category MiB columns, zero for absence,
|
|
unknown sizes after access failures, cross-drive storage, server exclusions, no
|
|
duplicate diagnostic lines, and usage staying out of savings totals.
|
|
|
|
References: [OS ProductType](https://learn.microsoft.com/en-us/windows/win32/cimwin32prov/win32-operatingsystem),
|
|
[Disk Cleanup](https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/cleanmgr),
|
|
[component cleanup](https://learn.microsoft.com/en-us/windows-hardware/manufacture/desktop/clean-up-the-winsxs-folder),
|
|
[component analysis](https://learn.microsoft.com/en-us/windows-hardware/manufacture/desktop/determine-the-actual-size-of-the-winsxs-folder?view=windows-11),
|
|
[shadow-storage measurements](https://learn.microsoft.com/en-us/previous-versions/windows/desktop/vsswmi/win32-shadowstorage),
|
|
[Windows Search](https://learn.microsoft.com/troubleshoot/windows-client/shell-experience/windows-search-performance-issues).
|