From 95616d45c7d336856cd955a277f2fe589145ebab Mon Sep 17 00:00:00 2001 From: Tw93 Date: Sat, 21 Mar 2026 13:26:20 +0800 Subject: [PATCH] fix(windows): skip unresolved system volume optimization Refs #604 --- bin/optimize.ps1 | 33 ++++++++++++++++++++++++++++++++- tests/Commands.Tests.ps1 | 7 +++++++ 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/bin/optimize.ps1 b/bin/optimize.ps1 index ada13fe..70d13aa 100644 --- a/bin/optimize.ps1 +++ b/bin/optimize.ps1 @@ -133,6 +133,21 @@ function Get-SystemDriveLetter { return $match.Value.ToUpperInvariant() } +function Test-SystemDriveOptimizable { + param( + [Parameter(Mandatory = $true)] + [string]$DriveLetter + ) + + $getVolume = Get-Command Get-Volume -ErrorAction SilentlyContinue + if (-not $getVolume) { + return $true + } + + $volume = Get-Volume -DriveLetter $DriveLetter -ErrorAction SilentlyContinue | Select-Object -First 1 + return ($null -ne $volume) +} + function Optimize-DiskDrive { <# .SYNOPSIS @@ -155,15 +170,31 @@ function Optimize-DiskDrive { return } + if (-not (Get-Command Optimize-Volume -ErrorAction SilentlyContinue)) { + Write-Host " $esc[90mDisk optimization skipped: Optimize-Volume is not available on this system$esc[0m" + return + } + try { $systemDriveLetter = Get-SystemDriveLetter + if (-not (Test-SystemDriveOptimizable -DriveLetter $systemDriveLetter)) { + Write-Host " $esc[90mDisk optimization skipped: Windows could not resolve drive ${systemDriveLetter} to an optimizable volume$esc[0m" + return + } + Write-Host " Running Windows default optimization on drive ${systemDriveLetter}:..." $null = Optimize-Volume -DriveLetter $systemDriveLetter -ErrorAction Stop Write-Host " $esc[32m$($script:Icons.Success)$esc[0m Drive optimization completed" $script:OptimizationsApplied++ } catch { - Write-Host " $esc[31m$($script:Icons.Error)$esc[0m Disk optimization failed: $_" + $message = $_.Exception.Message + if ($message -match 'MSFT_Volume' -or $message -match 'DriveLetter') { + Write-Host " $esc[90mDisk optimization skipped: Windows could not resolve drive ${systemDriveLetter} to an optimizable volume$esc[0m" + return + } + + Write-Host " $esc[31m$($script:Icons.Error)$esc[0m Disk optimization failed: $message" } } diff --git a/tests/Commands.Tests.ps1 b/tests/Commands.Tests.ps1 index 6536cb8..58b8dde 100644 --- a/tests/Commands.Tests.ps1 +++ b/tests/Commands.Tests.ps1 @@ -61,6 +61,13 @@ Describe "Optimize Command" { $result = & powershell -ExecutionPolicy Bypass -File "$script:BinDir\optimize.ps1" -ShowHelp 2>&1 $result -join "`n" | Should -Match "DryRun|Disk|DNS" } + + It "Should guard disk optimization when the system drive cannot be resolved to a volume" { + $source = Get-Content "$script:BinDir\optimize.ps1" -Raw + $source | Should -Match "function Test-SystemDriveOptimizable" + $source | Should -Match "Get-Volume -DriveLetter" + $source | Should -Match "Disk optimization skipped:" + } } }