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


<#
.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.1.4
    Run as Administrator.
#>

#Requires -RunAsAdministrator

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

# ── 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
                }
        } 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 }
}

# ── 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
    }

    $shellbags = @(
        "HKCU:\SOFTWARE\Microsoft\Windows\Shell\BagMRU",
        "HKCU:\SOFTWARE\Microsoft\Windows\Shell\Bags",
        "HKCU:\SOFTWARE\Classes\Local Settings\Software\Microsoft\Windows\Shell\BagMRU",
        "HKCU:\SOFTWARE\Classes\Local Settings\Software\Microsoft\Windows\Shell\Bags"
    )
    foreach ($p in $shellbags) {
        if (Test-Path $p) { Remove-Item $p -Recurse -Force }
    }

    $mru = @(
        "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\RecentDocs",
        "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\RunMRU"
    )
    foreach ($k in $mru) {
        if (Test-Path $k) {
            Get-ChildItem $k | Remove-Item -Recurse -Force
        }
    }
}

# ── Event logs (хирургично — только USB-специфичные) ───────────────────────
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 — вырезаем USB-секции ─────────────────────────────────
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
}

# ── 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 "[$(Get-Date -Format 'HH:mm:ss')] Scan complete." -ForegroundColor Green
}

Invoke-StorageScan