
# Safely wipes any Lx registrations from the Windows Registry
# Use this to wipe stale items as well

Set-StrictMode -Version Latest

# 1 = preview changes without deleting anything
# 0 = actually remove matching registry values and keys
$dryRun = 0

if ($dryRun) {
	Write-Host "Simulating Lx registry cleanup:"
} else {
	Write-Host "Running Lx registry cleanup:"
}

Write-Host "Removing Lx classes..."

$classesRoot =
	"Registry::HKEY_CURRENT_USER\Software\Classes"

$lxSettingsKey =
	"Registry::HKEY_CURRENT_USER\Software\Lx"

$registeredApplicationsKey =
	"Registry::HKEY_CURRENT_USER\Software\RegisteredApplications"

# Remove all HKCU\Software\Classes\Lx.File.* keys
Get-ChildItem $classesRoot -ErrorAction SilentlyContinue |
    Where-Object {
        $_.PSChildName -like "Lx.File.*"
    } |
    ForEach-Object {
        if ($dryRun) {
            Write-Host "  Would remove: $($_.Name)"
        } else {
            Write-Host "  Remove: $($_.Name)"
            Remove-Item $_.PSPath -Recurse -Force
        }
    }

Write-Host "Removing Lx links..."

# Remove all OpenWithProgids values named Lx.File.*
# from HKCU\Software\Classes\.<extension>\OpenWithProgids

Get-ChildItem $classesRoot -ErrorAction SilentlyContinue |
    Where-Object {
        $_.PSChildName -like ".*"
    } |
    ForEach-Object {
        $openWithProgids = Join-Path $_.PSPath "OpenWithProgids"

        if (Test-Path $openWithProgids) {
            $key = Get-Item $openWithProgids

            foreach ($valueName in $key.GetValueNames()) {
                if ($valueName -like "Lx.File.*") {
                    if ($dryRun) {
                        Write-Host "  Would remove: $openWithProgids -> $valueName"
                    } else {
                        Write-Host "  Remove: $openWithProgids -> $valueName"

                        Remove-ItemProperty `
                            -Path $openWithProgids `
                            -Name $valueName `
                            -ErrorAction SilentlyContinue
                    }
                }
            }
        }
    }

Write-Host "Removing Lx registration..."

# Remove exact key: HKCU\Software\Lx
if (Test-Path $lxSettingsKey) {
    if ($dryRun) {
        Write-Host "  Would remove: $lxSettingsKey"
    } else {
        Write-Host "  Remove: $lxSettingsKey"
        Remove-Item $lxSettingsKey -Recurse -Force
    }
}

# Remove exact value: HKCU\Software\RegisteredApplications -> Lx
if (Test-Path $registeredApplicationsKey) {
    $key = Get-Item $registeredApplicationsKey

    if ($key.GetValueNames() -ccontains "Lx") {
        if ($dryRun) {
            Write-Host "  Would remove: $registeredApplicationsKey -> Lx"
        } else {
            Write-Host "  Remove: $registeredApplicationsKey -> Lx"

            Remove-ItemProperty `
                -Path $registeredApplicationsKey `
                -Name "Lx" `
                -ErrorAction SilentlyContinue
        }
    }
}

Write-Host "All done."
