# Function reference

# On this page

  • Function list
  • Function reference (selected helpers)
    • Write-CustomMessage
    • Get-RecycleBinSize
    • Invoke-DISM-Safe
    • Invoke-RemoveWithRetry

This page lists helper functions used by Win-Storage-Remediate.ps1 with a short description. Use these helpers when writing tests or adapting the script.

# Function list

Function Purpose
Clear-BrowserCache Per-user browser cache cleanup for common browsers (Chrome, Edge, Firefox) using pruned enumeration and protected-path guards.
Clear-BrowserCacheAllUsers High-level routine to clear browser caches across user profiles (safe, pruned, and DryRun-aware).
Clear-DeliveryOptimizationAdvanced Advanced Delivery Optimization content cleanup for ProgramData locations (safe, non-service-disrupting removals).
Clear-DeliveryOptimizationCache Enumerates Delivery Optimization cache locations and removes safe content (pruned enumerator and protected-path checks apply).
Clear-OneDriveUserCache Per-user OneDrive cache cleaner. Avoids user documents and config files; walks directories using a stack-based enumerator to avoid reparse point traversal.
Clear-SoftwareDistributionDownload Cleans Windows Update download cache (SoftwareDistribution\\Download) using pruned enumeration.
Clear-WindowsUpdateDownloadCache Cautious Windows Update download folder cleaner (non-rebooting).
Export-EventLog Wrapper around wevtutil epl to export event logs with fallbacks for problematic channel names and quoted argument invocation.
Format-Size Small helper to convert bytes to human-friendly MB/GB strings for output.
Get-BrowserCachePathsForUser Helper that returns common browser cache paths for a given user profile (used by Clear-BrowserCacheAllUsers).
Get-ProbeSnapshot Read-only size probe: computes sizes for provided paths (used by -Estimate and diagnostic probes).
Get-RecycleBinSize Attempts to estimate Recycle Bin size via Shell.Application COM interface (best-effort; may return 0 if unavailable).
Get-SafeChildItems Safe directory enumerator that uses an explicit stack to walk folders and prunes branches that match skip/protected patterns. Use this instead of Get-ChildItem -Recurse for deletion passes.
Invoke-DISM-Safe DISM invocation wrapper that honours pending-reboot detection and the -ForceDISMWhenPending flag; logs exit codes and supports a WhatIf/DryRun fast path.
Invoke-GlobalTempCleanup Exposed cleanup pass for the machine/global TEMP folder (%TEMP).
Invoke-RemoveWithRetry Remove-Item wrapper with path canonicalisation, skip/protection checks, retry/backoff and timing/diagnostic messages.
Invoke-UserTempCleanup Exposed cleanup pass that removes per-user temp files under %USERPROFILE%\\AppData\\Local\\Temp using the safe enumerator and time budgets.
Invoke-WithRetry Generic retry wrapper that executes a provided scriptblock with configurable retries and backoff.
Merge-Log Safely consolidates the temporary runtime log into the main log. Uses file-stream copy with backoff and falls back to timestamped archive files or diagnostics if merging fails.
Resolve-FileLock Walks a directory tree (pruned) and reports on locked files; used to diagnose and optionally handle locked log files.
Save-MainLogArchive Creates per-run archives of the main log, preferring atomic Move-Item and falling back to append+truncate or diagnostic files.
Test-FileLock Lightweight check to determine whether a file is locked by attempting to open it exclusively.
Test-IsProtectedPath Canonical protection check used throughout the script; prevents touching the script's own logs/archives, reparse points, and other system-critical locations.
Test-IsSkipPath Matches a path against $skipPathPatterns (regex-first, with safe fallbacks). Returns true for paths that must not be removed or traversed.
Test-PendingReboot Detects common pending-reboot markers (Windows Update, CBS/Component-Based Servicing, PendingFileRenameOperations).
Wait-ForDISM Waits for any concurrent dism.exe processes to finish with a timeout.
Write-CustomMessage Centralised logging helper. Writes timestamped entries to the temporary log and respects the -Verbosity parameter (controls Write-Verbose/Write-Information behaviour).

# Function reference (selected helpers)

# Write-CustomMessage

  • Signature: Write-CustomMessage -Message <string> [-Level <string>] [-Verbose]
  • Purpose: Centralised log-first writer used throughout the remediation script.
  • Parameters:
    • Message: The textual message to record.
    • Level: Optional severity string (for example, 'INFO', 'WARN', 'ERROR'). Defaults to 'INFO' when omitted.
    • Verbose: When supplied (or when the run is started with -Verbosity Verbose), the function emits Write-Verbose output in addition to appending to the temp log.
  • Behaviour:
    • Always appends a timestamped, single-line entry to the per-run temporary log file (located in %TEMP%).
    • Emits host verbose output only when verbosity is enabled; this keeps Intune-captured host output compact while preserving detailed diagnostics in the temp log.
    • Sanitises input to avoid logging PII in host output; full details remain in the temp log only.
  • Return: None (writes to log and optionally to the host verbose stream).

# Get-RecycleBinSize

  • Signature: Get-RecycleBinSize [-Path <string>] [-AsInt64]
  • Purpose: Best-effort estimation of Recycle Bin usage for the specified volume or the system volume.
  • Parameters:
    • Path: Optional path or drive spec used to scope the probe. If omitted the function probes the system (C:) bin.
    • AsInt64: When present the function returns a stable [int64] value.
  • Behaviour:
    • Attempts a Shell.Application COM query first (the most accurate when available).
    • If COM is unavailable or fails, falls back to a conservative per-user Recycle.Bin enumeration and normalises the result to an [int64] number of bytes.
    • May return 0 when the bin cannot be probed due to access restrictions (for example running under different accounts or as SYSTEM in some hosts).
  • Return: [int64] number of bytes (0 when unknown or inaccessible).

# Invoke-DISM-Safe

  • Signature: Invoke-DISM-Safe [-WhatIf] [-ForceDISMWhenPending] [-TimeoutSec <int>]
  • Purpose: Run DISM component store cleanup while respecting pending-reboot detection and ShouldProcess semantics.
  • Parameters:
    • WhatIf: Honour ShouldProcess dry-run semantics (the function supports -WhatIf/-Confirm).
    • ForceDISMWhenPending: Overrides pending-reboot gating and forces DISM to run even when a reboot is pending.
    • TimeoutSec: Optional timeout (seconds) for the DISM call.
  • Behaviour:
    • Detects common pending-reboot markers and will skip DISM unless ForceDISMWhenPending is supplied or the file-level preference $Pref_ForceDISMWhenPendingOverride is set.
    • Calls Wait-ForDISM to ensure no concurrent dism.exe processes are running (with retries/backoff).
    • Logs exit codes, duration, and relevant diagnostics to the per-run temp log.
    • Declared with SupportsShouldProcess so callers can use -WhatIf safely in tests.
  • Return: [int] DISM exit code (0 for success). See logs for details on non-zero values.

# Invoke-RemoveWithRetry

  • Signature: Invoke-RemoveWithRetry -Path <string> [-Retries <int>] [-BackoffMs <int>] [-DryRun]
  • Purpose: Safe removal helper that canonicalises paths, checks skip/protected patterns, and retries common transient failure modes.
  • Parameters:
    • Path: Full path to remove (file or directory). The helper performs canonicalisation and protection checks.
    • Retries: Number of retry attempts (default: 3).
    • BackoffMs: Milliseconds to wait between retries (default: 500).
    • DryRun: When supplied, the helper logs what it would remove without performing destructive actions.
  • Behaviour:
    • Verifies that the target path is not a protected or skip-path using Test-IsProtectedPath/Test-IsSkipPath.
    • Attempts removal with Remove-Item -Force -Recurse (when safe) and retries on transient errors such as sharing violations.
    • Writes per-attempt diagnostics to the per-run temp log; only concise summaries are emitted to the host.
  • Return: [bool] true on successful removal or when DryRun is set; false on permanent failure (details in the per-run temp log).