Hardened Win-Storage-Remediate.ps1 for Intune/Proactive Remediations and safety-first automated deployment. Key changes:
Added runtime safety switches and modes: -DryRun, -SKIP_SLOW_IO, -CleanMgrOnly, -Estimate, -ForceDISMWhenPending, and -Verbosity (ValidateSet: Silent,Normal,Verbose). These provide non-destructive testing, opt-outs for long I/O, narrow testing modes and controlled DISM behaviour when a reboot is pending.
Implemented aggressive and conservative skip rules for OneDrive / ODL and other protected paths via a curated $skipPathPatterns list to avoid deleting synced or important files.
Implemented robust per-item retry/backoff logic for file and directory removals and other IO operations to tolerate transient locks and reduce partial failures.
Added time-budgeting controls (configurable $MaxCleanupDurationMinutes) for long enumerations so the script cannot run indefinitely on slow or locked file trees.
Hardened logging and archival:
Centralised temporary and main logs with Start-Transcript and Write-Log.
Prefer atomic archival via Move-Item into per-run archives; fallback to append+truncate into a single archive file, and final fallback diagnostic .diag.txt when archive operations fail.
Consolidation of temporary logs into the main log made DryRun-aware and simplified for robust parsing and token-checker compatibility.
Added a DISM safety wrapper (Invoke-DISM-Safe) which respects pending reboot detection and optionally runs when -ForceDISMWhenPending is supplied. Its exit codes and results are logged explicitly.
Added small utility wrappers: Invoke-RemoveWithRetry, Get-SafeChildItems (enumeration with skip rules), and Invoke-WithRetry to standardise retry/backoff behaviour across the script.
Performed linter-focused fixes and naming improvements to satisfy PSScriptAnalyzer guidance:
Replaced an unapproved verb name (Sweep-BrowserCache-AllUsers) with an approved verb (Clear-BrowserCacheAllUsers).
Fixed catch/string interpolation to use explicit formatting and avoid invalid variable-colon interpolation.
Silenced unused-variable warnings via intentional no-op references where variables are retained for future tuning (for example $null = $MaxCleanupDurationMinutes, $null = $skipPathPatterns).
Simplified and stabilised the final log-consolidation/archival region (previously a complex pipeline) to a conservative Read→Add-Content -Value→Remove-Item flow to avoid tokenisation/parser sensitivity in repository tooling.
Removed or repaired small corrupted/escaped fragments and ensured the script is accepted by the PowerShell parser (parser API) while further token-level scanner cleanups are in progress.
Exposed configuration variables and parameters for Intune-friendly usage; documented behaviour for Proactive Remediations and non-PR deployment scenarios.
#18/10/2025:
Reorganized all functions to be placed at the top of the script, immediately after the variables and before any code execution.
Grouped related sections of the main script logic into logical blocks for better readability and maintainability.
Ensured Disk Cleanup GUI suppression logic is placed near the Disk Cleanup execution section.
Consolidated log handling and finalization steps into a dedicated section at the end of the script.
Improved overall script structure to ensure logical order of operations and maintainability.
#17/10/2025:
Integrated CleanMgr registry preparation for selected VolumeCaches and invoked CleanMgr (/sagerun:1).
Configured and triggered Storage Sense to remove temporary files and locally cached OneDrive content.
Added DISM component store cleanup (StartComponentCleanup) with explicit exit-code logging.
Added removal of user-specific temporary files (%USERPROFILE%\AppData\Local\Temp).
Enhanced event log cleanup:
Exported logs to an archive directory ($env:TEMP\EventLogArchives) using wevtutil epl.
Logged the location of exported logs for archival purposes.
Cleared logs using wevtutil cl after successful export.
Improved error handling for individual logs to ensure the script continues processing other logs.
Added removal of old user profiles from C:\Users based on retention days ($userProfileRetentionDays).
Centralised logging with Start-Transcript and Write-Log; log file located at $env:TEMP<scriptName>.log.
Improved error handling so individual step failures are logged as warnings and the script continues.
Exposed configuration variables for operational tuning:
$oneDriveCleanupThreshold: Threshold for OneDrive content cleanup.
$userProfileRetentionDays: Retention period for user profiles.
$cleanupTypeSelection: Categories for CleanMgr cleanup.
$logsToClear: List of event logs to process.
Added initialisation of $freeSpaceGB to capture baseline free space before cleanup, ensuring accurate space-recovered reporting.
Documented exit codes:
0 = Success (normal completion).
1 = General failure (useful for external monitoring; individual step failures do not necessarily change the final exit code unless a fatal condition is detected).
Known issues (as-written):
None identified after recent updates.
#1/07/2025:
Major update
Improved documentation and logging output, especially if run manually at command line
Additional space gains by targeting Temporary files, and unused local OneDrive files via Storage Sense
Cleans up superseded Windows Update components from local device