Skip to content

Add optimize-windows.ps1 Windows optimization script - #7481

Open
HASSanHASSgit wants to merge 1 commit into
microsoft:mainfrom
HASSanHASSgit:hassanhassgit-glowing-waddle
Open

Add optimize-windows.ps1 Windows optimization script#7481
HASSanHASSgit wants to merge 1 commit into
microsoft:mainfrom
HASSanHASSgit:hassanhassgit-glowing-waddle

Conversation

@HASSanHASSgit

@HASSanHASSgit HASSanHASSgit commented Aug 3, 2026

Copy link
Copy Markdown

Motivation & Context

This change adds a PowerShell utility to automate Windows cleanup and performance optimization. It addresses the need for a repeatable maintenance tool that safely previews actions by default and offers an aggressive execution mode for administrators who want to reclaim resources and remove unnecessary temp/cache files.

Description & Review Guide

  • What are the major changes?
    • Adds optimize-windows.ps1: a PowerShell script that performs a dry-run by default and supports -Execute, -Aggressive, -Force, and -Reboot flags to apply changes. It logs actions and writes a manifest of deletions and terminated processes.
  • What is the impact of these changes?
    • No runtime changes to existing code. This is a new admin utility file; it does not modify runtime libraries or services unless explicitly run with -Execute.
  • What do you want reviewers to focus on?
    • Correctness and safety of the operations (whitelist of critical processes/services, temp paths targeted for deletion, and scope of service stoppage in aggressive mode). Also review logging/manifest behavior and admin-run assumptions.

Related Issue

N/A

Contribution Checklist

  • The code builds clean without any errors or warnings
  • All unit tests pass, and I have added new tests where possible
  • The PR follows the Contribution Guidelines (https://github.com/microsoft/agent-framework/blob/main/CONTRIBUTING.md)
  • This PR is linked to an issue and there is no other open PR for this issue (see Related Issue above).
  • This is not a breaking change. If it is a breaking change, add the breaking change label (or add "[BREAKING]" to the title prefix).

…-run default)

Adds a PowerShell tool that performs safe dry-run by default and supports -Execute, -Aggressive, -Force, and -Reboot flags for real runs. Requires Administrator privileges. Logs actions and writes a manifest of deletions/terminated processes.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds a new administrative PowerShell utility (optimize-windows.ps1) intended to perform Windows cleanup/optimization with a dry-run default and optional execution/aggressive modes. This fits the repo as an operational/maintenance helper script rather than a runtime library change.

Changes:

  • Introduces optimize-windows.ps1 with logging plus a JSON manifest of actions.
  • Implements temp cleanup, recycle bin emptying, process termination heuristics, optional service stopping, DISM/SFC runs, and volume optimization.
  • Adds Windows Update cache clearing and optional reboot behavior when executed.
Suppressed comments (2)

optimize-windows.ps1:177

  • Service stop/disable entries are currently written into the manifest's terminated section. If you add a dedicated services section, update this append to write there so consumers can distinguish services from processes.
            if ($DoStop) {
                if ($svc.Status -ne 'Stopped') {
                    Stop-Service -Name $svc.Name -Force -ErrorAction Stop
                    Set-Service -Name $svc.Name -StartupType Disabled -ErrorAction SilentlyContinue
                    Append-Manifest -manifestPath $manifest -section 'terminated' -entry $entry
                    Log "Stopped & disabled service: $($svc.Name)"

optimize-windows.ps1:127

  • $procInfos is expensive to compute (Get-CimInstance Win32_Process) and is never used, which adds avoidable runtime overhead for every run.
    # Get process performance counters
    $procInfos = Get-CimInstance Win32_Process | ForEach-Object {
        $p = $_
        $owner = try { ($p | Invoke-CimMethod -MethodName GetOwner).User } catch { '' }
        [PSCustomObject]@{

Comment thread optimize-windows.ps1
foreach ($it in $items) {
# Skip reparse points, system-critical files
if ($it.Attributes -band [IO.FileAttributes]::ReparsePoint) { continue }
$entry = @{Path=$it.FullName; Length=$it.Length; LastWrite=$it.LastWriteTime.ToString()}
Comment thread optimize-windows.ps1
Comment on lines +137 to +160
# Use Get-Process for CPU % via sampling
$samples = Get-Process | Select-Object Id, ProcessName, CPU, WS
foreach ($s in $samples) {
$name = $s.ProcessName
if ($whitelist -contains $name) { continue }
$wsMB = [int]($s.WS / 1MB)
$cpu = if ($s.CPU) { [int]$s.CPU } else { 0 }
$shouldKill = $false
if ($cpu -ge $CpuThreshold -or $wsMB -ge $MemMBThreshold) { $shouldKill = $true }
if ($shouldKill) {
$entry = @{Name=$name; Id=$s.Id; CPU=$cpu; WS_MB=$wsMB}
if ($DoKill) {
try {
Stop-Process -Id $s.Id -Force -ErrorAction Stop
Append-Manifest -manifestPath $manifest -section 'terminated' -entry $entry
Log "Terminated process $name (PID $($s.Id)) CPU=$cpu WS_MB=$wsMB"
} catch {
Log "Failed to terminate $name (PID $($s.Id)): $($_.Exception.Message)"
}
} else {
Log "Would terminate $name (PID $($s.Id)) CPU=$cpu WS_MB=$wsMB"
}
}
}
Comment thread optimize-windows.ps1
Comment on lines +63 to +71
function Get-TempPaths {
return @(
$env:TEMP,
$env:TMP,
"$env:SystemRoot\Temp",
"$env:SystemRoot\SoftwareDistribution\Download",
"$env:SystemRoot\Prefetch"
) | Where-Object { $_ -and (Test-Path $_) } | Select-Object -Unique
}
Comment thread optimize-windows.ps1

# 8) Clear Windows Update cache (SoftwareDistribution)
$wuCache = "$env:SystemRoot\SoftwareDistribution\Download"
if (Test-Path $wuCache) {
Comment thread optimize-windows.ps1

function Create-BackupManifest {
$manifest = "$PSScriptRoot\optimize-backup-$(Get-Date -Format yyyyMMdd-HHmmss).json"
@{created=(Get-Date); deletions=@(); terminated=@()} | ConvertTo-Json | Out-File -FilePath $manifest -Encoding UTF8
Comment thread optimize-windows.ps1
foreach ($d in $drives) {
if ($DoOptimize) {
try {
Optimize-Volume -DriveLetter $d.DriveLetter -Defrag -Verbose -ErrorAction Stop
Comment thread optimize-windows.ps1
Comment on lines +54 to +60
function Append-Manifest {
param($manifestPath, $section, $entry)
$json = Get-Content $manifestPath -Raw | ConvertFrom-Json
$list = $json.$section
$list += $entry
$json.$section = $list
$json | ConvertTo-Json | Out-File -FilePath $manifestPath -Encoding UTF8
@moonbox3

moonbox3 commented Aug 4, 2026

Copy link
Copy Markdown
Contributor

@HASSanHASSgit, again no issue is attached to this PR. Why do we need this change?

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants