Foro de elhacker.net

Programación => Scripting => Mensaje iniciado por: Eleкtro en 4 Marzo 2024, 15:10 pm



Título: [APORTE] [PowerShell] Remove Windows Installer product registration for missing MSI packages
Publicado por: Eleкtro en 4 Marzo 2024, 15:10 pm
El siguiente script desarrollado en Powershell sirve para realizar un tipo de limpieza que CCleaner y limpiadores especializados del registro (como por ejemplo Wise Registry Cleaner) no pueden llevar a cabo:

Limpiar todo rastro, en el registro de Windows, de entradas a instaladores MSI que no se encuentren presentes en el sistema o que simplemente den conflictos pos fallas de instalación o desinstalación.

Es magia pura para solucionar cierto tipo de problemas relacionados con entradas de registro de paquetes MSI huérfanos.

Autor del código original: https://gist.github.com/heaths/77fbe0b44496960fab25c2eb0b9e8475

(http://i.imgur.com/B0oG7Bcl.png) (https://i.imgur.com/B0oG7Bc.png)

Código
  1. #Requires -Version 3
  2.  
  3. # https://gist.github.com/heaths/77fbe0b44496960fab25c2eb0b9e8475
  4.  
  5. [CmdletBinding(SupportsShouldProcess = $true)]
  6. param (
  7.    [Parameter(Position = 0, ValueFromPipeline = $true)]
  8.    [ValidateNotNullOrEmpty()]
  9.    [string[]] $ProductCode
  10. )
  11.  
  12. [System.Console]::Title = "Remove Windows Installer product registration for missing MSI packages"
  13. [CultureInfo]::CurrentUICulture = "en-US"
  14.  
  15. try { Set-ExecutionPolicy -ExecutionPolicy "Unrestricted" -Scope "Process" } catch { }
  16.  
  17. $ErrorActionPreference = 'Stop'
  18. [int[]] $translation = 7,6,5,4,3,2,1,0,11,10,9,8,15,14,13,12,17,16,19,18,21,20,23,22,25,24,27,26,29,28,31,30
  19.  
  20. $loc = data {
  21.    ConvertFrom-StringData @'
  22.        Error_Elevation_Required = You must run this script in an elevated command prompt
  23.        Error_64Bit_Required = You must run this in a 64-bit command prompt
  24.        Error_PackageManagement_Required = Please install PackageManagement from http://go.microsoft.com/fwlink/?LinkID=746217
  25.        Process_Remove_Args1 = Remove registration for {0}
  26.        Verbose_Install_MSI = Installing the "MSI" module
  27.        Verbose_Scan_Missing = Scanning for products missing cached packages
  28.        Verbose_Remove_Key_Args1 = Removing key  : {0}
  29.        Verbose_Remove_Value_Args2 = Removing value: {0}\\{1}
  30.        Verbose_Remove_Source_Reg = Removing source registration
  31.        Verbose_Remove_Product_Reg = Removing product registration
  32.        Verbose_Remove_Upgrade_Reg = Removing upgrade registration
  33.        Verbose_Remove_Component_Reg = Removing component registration
  34.        Verbose_Found_Source_Args2 = Cache missing for {0} but found source at {1}
  35. '@
  36. }
  37.  
  38. $identity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
  39. $principal = New-Object System.Security.Principal.WindowsPrincipal $identity
  40. if (!$principal.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)) {
  41.    throw $loc.Error_Elevation_Required
  42. }
  43.  
  44. if ([System.Environment]::Is64BitOperatingSystem) {
  45.    if (![System.Environment]::Is64BitProcess) {
  46.        throw $loc.Error_64Bit_Required
  47.    }
  48. }
  49.  
  50. $pack = {
  51.    param (
  52.        [string] $Guid
  53.    )
  54.  
  55.    if (!$Guid) {
  56.        return
  57.    }
  58.  
  59.    $Guid = (New-Object System.Guid $Guid).ToString("N").ToUpperInvariant()
  60.  
  61.    $sb = New-Object System.Text.StringBuilder $translation.Count
  62.    foreach ($i in $translation) {
  63.        $null = $sb.Append($Guid[$i])
  64.    }
  65.  
  66.    $sb.ToString()
  67. }
  68.  
  69. $test = {
  70.    param (
  71.        $Product
  72.    )
  73.  
  74.    if ($Product.PSPath -and ($Product | Test-Path)) {
  75.        return $true
  76.    }
  77.  
  78.    if ($Product.PackageName) {
  79.        $Product | Get-MSISource | ForEach-Object {
  80.            $path = Join-Path $_.Path $Product.PackageName
  81.            if ($path | Test-Path) {
  82.                Write-Host ($loc.Verbose_Found_Source_Args2 -f $Product.ProductCode, $path)
  83.                return $true
  84.            }
  85.        }
  86.    }
  87.  
  88.    $false
  89. }
  90.  
  91. $remove = {
  92.    param (
  93.        [string] $Key
  94.    )
  95.  
  96.    if (Test-Path $Key) {
  97.        Write-Host ($loc.Verbose_Remove_Key_Args1 -f $Key)
  98.        Remove-Item -Recurse -Force $Key
  99.    }
  100. }
  101.  
  102. $removeChild = {
  103.    param (
  104.        [string] $Key,
  105.        [string] $Name
  106.    )
  107.  
  108.    if (Test-Path $Key) {
  109.        Get-ChildItem $Key | ForEach-Object {
  110.            $obj = $_ | Get-ItemProperty
  111.            if ($obj.$Name -ne $null) {
  112.                Write-Host ($loc.Verbose_Remove_Value_Args2 -f $_.Name, $Name)
  113.                Remove-ItemProperty -Force -Name $Name -LiteralPath $_.PSPath
  114.  
  115.                $obj = Get-ItemProperty -LiteralPath $_.PSPath
  116.                if (!$obj) {
  117.                    Write-Host ($loc.Verbose_Remove_Key_Args1 -f $_.Name)
  118.                    Remove-Item -Recurse -Force -LiteralPath $_.PSPath
  119.                }
  120.            }
  121.        }
  122.    }
  123. }
  124.  
  125. if (!$ProductCode) {
  126.    # Install the MSI module if missing.
  127.    if (!(Get-Module -ListAvailable MSI)) {
  128.        Write-Host $loc.Verbose_Install_MSI
  129.  
  130.        # Make sure PackageManagement is installed (comes with WMF 5.0 / Windows 10).
  131.        if (!(Get-Module -ListAvailable PackageManagement)) {
  132.            throw $loc.Error_PackageManagement_Required
  133.        }
  134.  
  135.        Install-Module MSI -Scope CurrentUser -SkipPublisherCheck -Force
  136.    }
  137.  
  138.    Write-Host $loc.Verbose_Scan_Missing
  139.    foreach ($msi in (Get-MSIProductInfo -UserContext Machine)) {
  140.        if (!(&$test $msi)) {
  141.            $ProductCode += $msi.ProductCode
  142.        }
  143.    }
  144. }
  145.  
  146. foreach ($code in $ProductCode) {
  147.    if ($PSCmdlet.ShouldProcess($msi, $loc.Process_Remove_Args1 -f $code)) {
  148.        $packedProductCode = &$pack $code
  149.  
  150.        Write-Host $loc.Verbose_Remove_Source_Reg
  151.        &$remove "Registry::HKCL\SOFTWARE\Classes\Installer\Products\$packedProductCode"
  152.        &$remove "Registry::HKCL\SOFTWARE\Classes\Installer\Features\$packedProductCode"
  153.        &$remove "Registry::HKLM\SOFTWARE\Classes\Installer\Products\$packedProductCode"
  154.        &$remove "Registry::HKLM\SOFTWARE\Classes\Installer\Features\$packedProductCode"
  155.  
  156.        Write-Host $loc.Verbose_Remove_Product_Reg
  157.        &$remove "Registry::HKCL\SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\UserData\S-1-5-18\Products\$packedProductCode"
  158.        &$remove "Registry::HKCL\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$code"
  159.        &$remove "Registry::HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\UserData\S-1-5-18\Products\$packedProductCode"
  160.        &$remove "Registry::HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$code"
  161.        &$remove "Registry::HKLM\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\$code"
  162.  
  163.        Write-Host $loc.Verbose_Remove_Upgrade_Reg
  164.        &$removeChild "Registry::HKCL\SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\UpgradeCodes" $packedProductCode
  165.        &$removeChild "Registry::HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\UpgradeCodes" $packedProductCode
  166.  
  167.        Write-Host $loc.Verbose_Remove_Component_Reg
  168.        &$removeChild "Registry::HKCL\SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\UserData\S-1-5-18\Components" $packedProductCode
  169.        &$removeChild "Registry::HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\UserData\S-1-5-18\Components" $packedProductCode
  170.  
  171.    }
  172. }
  173.  
  174. Write-Host "Press any key to exit..."
  175. $key = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
  176. Exit(0)
  177.  
  178. <#
  179. .SYNOPSIS
  180. Removes Windows Installer product registrtation for missing or specified MSIs
  181. .DESCRIPTION
  182. If Windows Installer product registration is corrupt (exit code 1610) or package
  183. sources are missing (exit code 1603, error message 1714; or exit code 1612),
  184. you can use this script in an elevated PowerShell command shell to clean up the
  185. registration is a transactional manner to avoid making machine state worse.
  186. Please note that this should be a last resort and only for those issues above.
  187. The old msizap.exe program was frought with issues and can make matters worse
  188. if not used properly.
  189. .PARAMETER ProductCode
  190. Optional list of ProductCode to clean up; otherwise, ProductCodes are scanned
  191. from products with missing sources.
  192. .EXAMPLE
  193. PS> Unregister-MissingMSIs.ps1
  194. Removes per-machine product registration for products with missing cached MSIs.
  195. .EXAMPLE
  196. PS> Unregister-MissingMSIs.ps1 '{7B88D6BB-A664-4E5A-AB81-C435C8639A4D}'
  197. Remove per-machine product registration for the specified ProductCode only.
  198. #>