elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Guía actualizada para evitar que un ransomware ataque tu empresa


  Mostrar Temas
Páginas: [1] 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 ... 105
1  Foros Generales / Sugerencias y dudas sobre el Foro / [SOLUCIONADO] ¿Cómo desactivo o cambio el corrector ortográfico en el foro? en: 13 Abril 2024, 11:08 am
Este problema me sucede desde... no sé, desde hace años, pero no me ha dado por pedir ayuda, hasta ahora.

Quien me conozca un poco sabrá que suelo editar mucho mis posts, para corregir faltas, mejorar la redacción, añadir o borrar información (y a veces, cosas que me arrepiento de haber escrito tras haber reflexionado un poco xD), y cosas así. En parte es por que soy (o me considero) perfeccionista, y en parte también es por este problema que voy a explicar, que no me ayuda en nada para darme cuenta de algunos errores ortográficos o algunas teclas que acabo tecleando sin pretender hacerlo...

El caso es que, siempre que escribo algo en el foro, se me activa de forma automática el corrector de palabras EN INGLÉS.

Y no sé por qué se activa en Inglés, pero creo que no es una configuración de mi navegador (Firefox), por que en el resto de páginas no me sucede esto, solo en el foro.

Y entonces, cuando escribo algo, prácticamente todas las palabras en Español me aparecen así como si estuvieran mal escritas:



¿Alguien tiene idea de como puedo hacer para que se active el corrector en Español, o desactivarlo del todo (solo para el foro)?.

Gracias.
2  Programación / Scripting / [APORTE] [PowerShell] RAR.exe | Test RAR Files en: 5 Abril 2024, 00:39 am
El siguiente script, desarrollado en PowerShell y dependiente del programa de terceros WinRAR (rar.exe), sirve para analizar la integridad de los archivos RAR que haya en el directorio donde se ejecute el script.







El script genera un archivo con nombre "RAR_Test_Files.log" en el directorio de trabajo, donde se registran los nombres de archivos de los tests fallidos. En este ejemplo:

RAR_Test_Files.log
Citar
Código:
Failed test with exit code 3: C:\Nueva carpeta\Stupid Invaders (Spanish) (Disc 1)_128mb.rar



Test RAR Files.ps1
Código
  1. <#
  2. ===========================================================================================
  3. |                                                                                         |
  4. |                                        Variables                                        |
  5. |                                                                                         |
  6. ===========================================================================================
  7. #>
  8.  
  9. $rarExecutablePath = "${env:ProgramFiles}\WinRAR\rar.exe"
  10. $recursiveSearch   = $true
  11. $logErrorFilePath  = "$PSScriptRoot\RAR_Test_Files.log"
  12.  
  13. <#
  14. ===========================================================================================
  15. |                                                                                         |
  16. |                                    Functions                                            |
  17. |                                                                                         |
  18. ===========================================================================================
  19. #>
  20.  
  21. function Show-WelcomeScreen {
  22.    Clear-Host
  23.    Write-Host ""
  24.    Write-Host " $($host.ui.RawUI.WindowTitle)"
  25.    Write-Host " +===================================================+"
  26.    Write-Host " |                                                   |"
  27.    Write-Host " | This script will use RAR.exe to test each file in |"
  28.    Write-Host " | the current working directory, and inform about   |"
  29.    Write-Host " | any errors found during the test.                 |"
  30.    Write-Host " |                                                   |"
  31.    Write-Host " +===================================================+"
  32.    Write-Host ""
  33.    Write-Host " Script Settings            " -ForegroundColor DarkGray
  34.    Write-Host " ===========================" -ForegroundColor DarkGray
  35.    Write-Host " RAR Executable Path: $([System.IO.Path]::GetFullPath($rarExecutablePath))" -ForegroundColor DarkGray
  36.    Write-Host " Recursive Search...: $recursiveSearch" -ForegroundColor DarkGray
  37.    Write-Host ""
  38. }
  39.  
  40. function Confirm-Continue {
  41.    Write-Host " Press 'Y' key to continue or 'N' to exit."
  42.    Write-Host ""
  43.    Write-Host " -Continue? (Y/N)"
  44.    do {
  45.        $key = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
  46.        $char = $key.Character.ToString().ToUpper()
  47.        if ($char -ne "Y" -and $char -ne "N") {
  48.            [console]::beep(1500, 500)
  49.        }
  50.    } while ($char -ne "Y" -and $char -ne "N")
  51.    if ($char -eq "N") {Exit(1)} else {Clear-Host}
  52. }
  53.  
  54. function Test-RarFiles {
  55.    Write-Host "Fetching RAR files, please wait..." -ForegroundColor DarkGray
  56.    Write-Host ""
  57.  
  58.    $rarFiles = $null
  59.    if ($recursiveSearch) {
  60.        $rarFiles = Get-ChildItem -LiteralPath "$PSScriptRoot" -Filter "*.rar" -Recurse -File
  61.    } else {
  62.        $rarFiles = Get-ChildItem -LiteralPath "$PSScriptRoot" -Filter "*.rar" -File
  63.    }
  64.  
  65.    $rarFileCount = $rarFiles.Count
  66.    $currentFileCount = 0
  67.  
  68.    If ($rarFileCount -eq 0) {return}
  69.  
  70.    $testSuccessCount = 0
  71.    $testFailCount = 0
  72.  
  73.    $logStream = [System.IO.StreamWriter]::new($logErrorFilePath, $false)
  74.    foreach ($rarFile in $rarFiles) {
  75.        $currentFileCount +=1
  76.        Write-Host "RAR File $currentFileCount of $($rarFileCount):" -ForegroundColor DarkGray
  77.  
  78.        $psi = New-Object System.Diagnostics.ProcessStartInfo
  79.        $psi.FileName = $rarExecutablePath
  80.        $psi.Arguments = "t -idcdn `"$($rarFile.FullName)`""
  81.        $psi.RedirectStandardOutput = $false
  82.        $psi.UseShellExecute = $false
  83.        $psi.CreateNoWindow = $false
  84.  
  85.        $process = [System.Diagnostics.Process]::Start($psi)
  86.        $process.WaitForExit()
  87.        $exitCode = $process.ExitCode
  88.  
  89.        if ($exitCode -eq 0) {
  90.            Write-Host "RAR process exited with code: $exitCode" -ForegroundColor Green
  91.            $testSuccessCount +=1
  92.        } else {
  93.            Write-Warning "RAR process exited with code: $exitCode"
  94.            $logStream.WriteLine("Failed test with exit code $($exitCode): $($rarFile.FullName)")
  95.            $testFailCount +=1
  96.        }
  97.        Write-Host ""
  98.    }
  99.    $logStream.Close()
  100.  
  101.    $SuccessPercent = [string]::Format("{0:F0}", ($testSuccessCount / $currentFileCount) * 100)
  102.    if ($testSuccessCount -eq $currentFileCount) {
  103.        Write-Host "RAR Tests Successful: $testSuccessCount of $currentFileCount ($SuccessPercent%)" -BackgroundColor Black -ForegroundColor Green
  104.    } else {
  105.        Write-Warning "RAR Tests Successful: $testSuccessCount of $currentFileCount ($SuccessPercent%)"
  106.    }
  107.  
  108.    $FailPercent = [string]::Format("{0:F0}", ($testFailCount / $currentFileCount) * 100)
  109.    if ($testFailCount -eq 0) {
  110.        Write-Host "RAR Tests Failed....: $testFailCount of $currentFileCount ($FailPercent%)" -BackgroundColor Black -ForegroundColor Green
  111.    } else {
  112.        Write-Warning "RAR Tests Failed....: $testFailCount of $currentFileCount ($FailPercent%)"
  113.    }
  114.  
  115. }
  116.  
  117. function Show-GoodbyeScreen {
  118.    Write-Host ""
  119.    Write-Host "Operation Completed!" -BackgroundColor Black -ForegroundColor Green
  120.    Write-Host ""
  121.    Write-Host "Press any key to exit..."
  122.    $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown")
  123.    Exit(0)
  124. }
  125.  
  126. <#
  127. ===========================================================================================
  128. |                                                                                         |
  129. |                                         Main                                            |
  130. |                                                                                         |
  131. ===========================================================================================
  132. #>
  133.  
  134. [System.Console]::Title = "Test RAR Files - by Elektro"
  135. #[System.Console]::SetWindowSize(150, 45)
  136. [CultureInfo]::CurrentUICulture = "en-US"
  137.  
  138. try { Set-ExecutionPolicy -ExecutionPolicy "Unrestricted" -Scope "Process" } catch { }
  139.  
  140. Show-WelcomeScreen
  141. Confirm-Continue
  142. Test-RarFiles
  143. Show-GoodbyeScreen
  144.  
3  Foros Generales / Foro Libre / Illuminati: He recibido una invitación de membresía. en: 3 Abril 2024, 18:24 pm
A lo largo de mi vida he recibido muchos e-mails, que van desde invitaciones para multiplicar mi dinero en menos de 24 horas sin hacer nada, también he recibido e-mails de premios en casinos y loterías a los que nunca he jugado, viajes gratuitos en avión a lugares insospechados y con estancias también gratuitas, e incluso he llegado a recibir solicitudes para poder agilizar trámites burocráticos con el objetivo de transferirme una herencia millonaria de mis parientes perdidos en África, y en otras ocasiones favores de jeques millonarios de Arabia que necesitaban mi ayuda para poder sacar dinero de esos países a cambio de ofrecerme una sustanciosa parte millonaria del dinero por mi ayuda.

He sido muy afortunado con todo este tipo de e-mails, ¿verdad?. Soy tan afortunado que no dejo de recibirlos casi a diario. Tanto es así, que actualmente estoy a la espera de obtener 14 herencias, 8 donaciones millonarias, 5 premios en la loteria y 2 viajes a las Islas Caimán en lo que llevo contado del año 2024. Año tras año se me acumulan las riquezas.

Pero lo cierto es que hasta ahora no había recibido un e-mail tan deseado cómo este:



Traducción al Español para los plebeyos no iluminados:

Citar
Hola Elegidos de la Luz,

Fuiste elegido por la Gran Hermandad de los Illuminati para ser miembro de esta familia; Has encontrado el favor ante los ojos del Gran Creador y de ahí esta noble invitación a ser miembro de la Familia Elite.

¿Quieres unirte a la Gran Hermandad Illuminati para hacerte rico, famoso y protegido en la vida?. Únase a nosotros hoy y resuelva sus problemas financieros si desea convertirse en miembro de los Illuminati.

CONTÁCTENOS AHORA: illuminatirecruiter*******@gmail.com

Por favor envíe su respuesta únicamente al CORREO ELECTRÓNICO: illuminatirecruiter*******@gmail.com

Por supuesto pienso responder a este e-mail, a ver si me admiten en la élite. Qué ganas tengo.



Y hasta aquí las ironías. Evidentemente ese e-mail es un claro intento de SCAM; y me ha parecido original y divertido, por eso quise compartirlo con ustedes.

¿Alguna vez recibieron una invitación de los Illuminati como esta?. :xD

Encontré este interesante artículo de aquí abajo, aunque parece ser una metodología algo diferente:


Aténtamente,
Elektro.
4  Foros Generales / Sugerencias y dudas sobre el Foro / [SOLUCIONADO] He publicado catorce hilos en el lugar incorrecto y de forma absurda... en: 19 Marzo 2024, 01:09 am
Hola.

En la sección de programación general (https://foro.elhacker.net/programacion_general-b18.0/), en la primera página, publiqué varios hilos cuyos títulos empiezan con el prefijo "[APORTE]".

Pues todos esos hilos en realidad deberían ir en la sección de scripting.

Me he dado cuenta ahora, o mejor dicho he caído ahora en la cuenta de que estaban publicados en otra sección del foro, por que he publicado un nuevo aporte en la sección de scripting y no encontraba estos otros hilos ahí, y me ha extrañado, y pensé para mis adentros: "¿dónde coño están mis otros hilos, me los habrán borrado sin decir nada?" :xD.

El caso es que los publiqué en la sección de Programación General de forma inconsciente, no seguí ningún criterio en especial, simplemente fue un acto inconsciente publicarlos ahí en Programación General, pero en realidad todos esos aportes son de lenguajes de scripting, así que... no están en su sección adecuada.

Y es un poco absurdo, por que frecuentemente accedo a la sección de Programación General y veo mis hilos en la primera página de esa sección, y en todos los catorce hilos se puede ver perfectamente como comienzo el texto con frases similares a: "El siguiente script sirve para realizar tal cosa...", pero nada, que no he caído en la cuenta de que estaban publicados en la sección incorrecta, hasta ahora xD. Algo totalmente inconsciente por mi parte como ya digo.

Son 14 hilos. Puede resultar tedioso moverlos (ya no me acuerdo cómo de fácil o tedioso era), pero bueno, un error inconsciente lo podemos tener cualquiera, disculpen.

PD: Si alguien se había fijado en ello, quiero decir, que ese no era el lugar más indicado para ese tipo de aportes, ¡debería haberme dicho algo! (que no soy tan cascarrabias como algunos se pensarán).

Un saludo.
5  Programación / Scripting / [APORTE] [VBS] VMWare: Mount / Unmount Shared Folders Network Drive en: 19 Marzo 2024, 00:52 am
Los siguientes dos scripts, desarrollados en el lenguaje Visual Basic Script y que se deben usar en conjunto con una máquina virtual de VMWare (aunque se pueden modificar para Virtual Box), sirven como atajo para montar y desmontar la unidad de red de las "carpetas compartidas" (shared folders).

Utilizar estos scripts nos ahorra un valioso tiempo al no tener que usar el cliente de VMWare para abrir el menú de opciones donde desactivar y reactivar las carpetas compartidas.

La idea tras esta simple herramienta es eso, ahorrar tiempo, y de esta manera poder aislar la máquina virtual del sistema operativo anfitrión impidiendo el acceso a la unidad de red de las carpetas compartidas, y volver a habilitar el acceso, tan solo haciendo dos clicks para ejecutar estos scripts.



Mount Shared Folders Network Drive.vbs
Código
  1. ' Mount VMWare Shared Folders Network Drive
  2.  
  3. Option Explicit
  4.  
  5. Dim objFSO, objShell, objNetwork, colDrives, colNetDrives, i, msg
  6. Dim objDrive, vmWareDrive, vmWarePath, drive, path
  7.  
  8. vmWareDrive = "Z:"
  9. vmWarePath  = "\\vmware-host\Shared Folders"
  10.  
  11. Set objFSO = CreateObject("Scripting.FileSystemObject")
  12. Set objShell = CreateObject("WScript.Shell")
  13. Set objNetwork = CreateObject("WScript.Network")
  14. Set colDrives = objFSO.Drives
  15. Set colNetDrives = objNetwork.EnumNetworkDrives
  16.  
  17. For i = 0 to colNetDrives.Count - 1 Step 2
  18. drive = colNetDrives.Item(i)
  19. path  = colNetDrives.Item(i+1)
  20.  
  21. If (LCase(drive) = LCase(vmWareDrive)) Then
  22. If (LCase(path) = LCase(vmWarePath)) Then
  23. msg = "A network drive is already mounted with same letter and UNC path:" & vbCrLf & vbCrLf
  24. msg = msg & drive & vbTab & """" & path & """"
  25. objShell.Popup msg, 20, "Warning: Network Drives", 48
  26. Else
  27. msg = "A network drive is already mounted with a different UNC path:" & vbCrLf & vbCrLf
  28. msg = msg & drive & vbTab & """" & path & """"
  29. objShell.Popup msg, 20, "Error: Network Drives", 16
  30. End If
  31. WScript.Quit()
  32. End If
  33. Next
  34.  
  35. For Each objDrive in colDrives
  36. drive = objDrive.DriveLetter & ":"
  37. If (LCase(drive) = LCase(vmWareDrive)) Then
  38. msg = "A local drive is already mounted with the same drive letter:" & vbCrLf & vbCrLf
  39. msg = msg & "Letter: " & drive & vbCrLf
  40. msg = msg & "FileSystem: " & objDrive.FileSystem & vbCrLf
  41. msg = msg & "Volume Name: " & objDrive.VolumeName & vbCrLf
  42. msg = msg & "Share Name: " & objDrive.ShareName
  43. objShell.Popup msg, 20, "Error: Network Drives", 16
  44. WScript.Quit()
  45. End If
  46. Next
  47.  
  48. objNetwork.MapNetworkDrive vmWareDrive, vmWarePath
  49.  
  50. msg = "The following network drive was successfully mounted:" & vbCrLf & vbCrLf
  51. msg = msg & vmWareDrive & vbTab & """" & vmWarePath & """"
  52. objShell.Popup msg, 20, "Info: Network Drives", 64
  53. WScript.Quit()



Unmount Shared Folders Network Drive.vbs
Código
  1. ' Unmount VMWare Shared Folders Network Drive
  2.  
  3. Option Explicit
  4.  
  5. Dim objShell, objNetwork, colDrives, i, msg
  6. Dim vmWareDrive, vmWarePath, drive, path
  7.  
  8. vmWareDrive = "Z:"
  9. vmWarePath  = "\\vmware-host\Shared Folders"
  10.  
  11. Set objShell = CreateObject("WScript.Shell")
  12. Set objNetwork = CreateObject("WScript.Network")
  13. Set colDrives = objNetwork.EnumNetworkDrives
  14.  
  15. For i = 0 to colDrives.Count - 1 Step 2
  16. drive = colDrives.Item(i)
  17. path  = colDrives.Item(i+1)
  18.  
  19. If (LCase(drive) = LCase(vmWareDrive)) Then
  20. If (LCase(path) = LCase(vmWarePath)) Then
  21. objNetwork.RemoveNetworkDrive vmWareDrive, True, True
  22.  
  23. msg = "The following network drive was successfully unmounted:" & vbCrLf & vbCrLf
  24. msg = msg & drive & vbTab & """" & path & """"
  25. objShell.Popup msg, 20, "Info: Network Drives", 64
  26. Else
  27. msg = "A network drive is already mounted with a different UNC path:" & vbCrLf & vbCrLf
  28. msg = msg & drive & vbTab & """" & path & """"
  29. objShell.Popup msg, 20, "Warning: Network Drives", 16
  30. End If
  31. WScript.Quit()
  32. End If
  33. Next
  34.  
  35. msg = "No matching network drive " & """" & vmWareDrive & """" & " was found."
  36. objShell.Popup msg, 20, "Error: Network Drives", 16
  37. WScript.Quit()
6  Media / Juegos y Consolas / Emuladores Yuzu y Citra: Aquí puedes descargar sus últimas versiones. en: 5 Marzo 2024, 13:59 pm
No me andaré con muchos rodeos, simplemente mencionaré lo importante para dar contexto, y es que Nintendo demandó a los creadores del emulador Yuzu para Nintendo Switch, que también son los creadores del emulador Citra para Nintendo 3DS, y desde aproximadamente el día 04/Marzo/2024 han desaparecido los repositorios de código abierto para ambos emuladores, y con ello, los enlaces de descarga a los emuladores.

En este hilo compartiré el método a llevar a cabo para que puedan descargar las últimas releases públicadas para ambos emuladores.

El contenido ofrecido en este hilo no es ilegal, son (eran) programas de código abierto con un gran apoyo por parte de su comunidad y reseñas en todo tipo de medios oficiales, además, en este hilo no se comparten descargas directas, y por supuesto el hecho de que una compañía demande a un individuo para preservar sus intereses comerciales eso ni por asomo lo convierte en una acción delictiva per se.

De todas formas y si a pesar de ello el staff considera que es mejor no publicar este tipo de contenido, no pondré objeción y pido disculpas, por supuesto.



La metodología consiste en usar la Wayback Machine de Internet Archive para acceder a la copia estática más reciente de los repositorios de ambos emuladores con sus correspondientes descargas:



(Para Windows deben descargar el archivo con extensión .zip, ya que no hay copia disponible para el archivo .7z y .tar.xz)




Cita de: Citra
La compilación Nightly se basa en la rama maestra y contiene funciones ya revisadas y probadas.

La compilación Canary se basa en la rama maestra, pero aún se están revisando características adicionales.



Eso sería todo. ¡Disfrútenlo mientras todavía se pueda! (mientras Nintendo no decida seguir arruinando más su imagen demandando a los de archive.org :xD).

Aténtamente,
Elektro.
7  Sistemas Operativos / Windows / [SOLUCIONADO] Busco algún programa cuyo instalador genere este tipo de archivo link... en: 5 Marzo 2024, 13:18 pm
Buenos días. No se si publicar esta solicitud aquí o en el foro libre (o tal vez en Software).

Yo lo veo más relacionado con aspectos relacionados con Windows, pero muévanlo donde prefieran.

El caso es que tengo la necesidad de encontrar algún software que se distribuya en forma de instalador, y que al momento de instalar dicho software se genere un acceso directo como el de la siguiente imagen, donde no se permite la modificación de la propiedad "Destino":



(lo siento por el idioma de la imagen XD)

Esa restricción a la hora de modificar el destino, se debe a que el acceso directo fue creado usando un identificador especial del sistema en lugar de haber utilizado una cadena de texto convencional ( más info: learn.microsoft.com - Item IDs ), y al parecer Windows deshabilita la caja de texto de la propiedad "Destino" para ese tipo de links que fueron creados de tal forma.

Bueno, pues no se me ocurre donde puedo encontrar y descargar un software / instalador que genere ese tipo de archivo de acceso directo (*.lnk). Me da igual si el programa es gratuito o de pago, es simplemente que me permita instalarlo y me genere ese archivo link para cuestiones de prueba en un entorno de programación.



Es evidente, por la imagen que he compartido, que el Microsoft Word al parecer genera ese tipo de archivo link, pero a mi me han pasado una ISO del Office 2016 de 2 GB, y a mi no me genera ese link. Quizás no estoy usando la ISO correcta.

Tengo conocimiento de que el emulador de video juegos por nombre "Yuzu", o tal vez era otro por nombre "Citra", creaban este tipo de archivo link, pero para mi mala suerte justo ayer cerraron sus sitios web (debido a una demanda por parte de la compañía Nintendo) y el instalador ya no funciona por que requiere acceso online.

Ahora no recuerdo otro programa que genere ese tipo de acceso directo. Se supone que hay aplicación de la Microsoft Store que cuando se instalan generan ese tipo de link, pero yo tengo la Microsoft Store capada de mi instalación de Windows. También se supone que hay video juegos que generan ese tipo de link en la carpeta integrada "Juegos" del menú inicio, pero esto también lo tengo parcialmente capado y de todas formas no se si habrá algún juego gratuito con el que probar a ver.

Gracias con antelación.
8  Programación / Scripting / [APORTE] [PowerShell] SetACL.exe | Get Full Registry Ownership en: 4 Marzo 2024, 15:31 pm
El siguiente script desarrollado en PowerShell y dependiente del programa de terceros SetACL (https://helgeklein.com/download/#), sirve para adquirir propiedad absoluta sobre todas las claves de registro del sistema, lo que puede servir en algunos escenarios de prueba (generalmente en máquinas virtuales), o de infecciones por malware.

UTILIZAR ESTE SCRIPT BAJO SU PROPIA RESPONSABILIDAD, Y BAJO UNA CUENTA DE ADMINISTRADOR.

MODIFICAR LOS PERMISOS DE ALGUNAS CLAVES DEL REGISTRO DE WINDOWS PUEDE CONLLEVAR CONSECUENCIAS IMPREVISTAS QUE PROVOQUEN UN MALFUNCIONAMIENTO DEL SISTEMA OPERATIVO E IMPIDAN INICIAR SESIÓN DE USUARIO.

NO ME HAGO RESPONSABLE DE NADA.






Código
  1. <#
  2. ===========================================================================================
  3. |                                                                                         |
  4. |                                    Functions                                            |
  5. |                                                                                         |
  6. ===========================================================================================
  7. #>
  8.  
  9. function Show-WelcomeScreen {
  10.    Clear-Host
  11.    Write-Output ""
  12.    Write-Output " $($host.ui.RawUI.WindowTitle)"
  13.    Write-Output " +====================================================================+"
  14.    Write-Output " |                                                                    |"
  15.    Write-Output " | This script will take the ownership and ACE (Access Control Entry) |"
  16.    Write-Output " | of all the registry keys and subkeys in the current computer,      |"
  17.    Write-Output " | giving full access and permissions for the current user.           |"
  18.    Write-Output " |                                                                    |"
  19.    Write-Output " +====================================================================+"
  20.    Write-Output ""
  21.    Write-Host   " CHANGING THE OWNER AND PERMISSIONS COULD BREAK THINGS," -ForegroundColor Red
  22.    Write-Host   " SO PROCEED WITH CAUTION AND DO IT AT YOUR OWN RISK !!" -ForegroundColor Red
  23.    Write-Output ""
  24.    Write-Output " CURRENT SCRIPT CONFIG:"
  25.    Write-Output " ----------------------"
  26.    Write-Output " -SetAclFilePath: $SetAclFilePath"
  27.    Write-Output " -UserName......: $UserName"
  28.    Write-Output " -RegKeys.......:"
  29.    Write-Output ($RegKeys | ForEach-Object {"                  $_"})
  30.    Write-Output ""
  31. }
  32.  
  33. function Confirm-Continue {
  34.    Write-Host " Press 'Y' key to continue or 'N' to exit."
  35.    Write-Host ""
  36.    Write-Host " -Continue? (Y/N)"
  37.    do {
  38.        $key = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
  39.        $char = $key.Character.ToString().ToUpper()
  40.        if ($char -ne "Y" -and $char -ne "N") {
  41.            [console]::beep(1500, 500)
  42.        }
  43.    } while ($char -ne "Y" -and $char -ne "N")
  44.    if ($char -eq "N") {Exit(1)} else {Clear-Host}
  45. }
  46.  
  47. function Get-RegistryOwnership {
  48.    param(
  49.        [string]$setAclFilePath = "$env:ProgramFiles\SetACL\setacl.exe",
  50.        [string[]]$regKeys,
  51.        [string]$userName = "$env:UserName"
  52.    )
  53.  
  54.    try {
  55.        if (-not (Test-Path $setAclFilePath)) {
  56.            $ex = New-Object System.IO.FileNotFoundException("SetACL.exe file not found at path '$setAclFilePath'.", $setAclFilePath)
  57.            throw $ex
  58.        }
  59.  
  60.        $logFile = New-TemporaryFile
  61.  
  62.        foreach ($key in $regKeys) {
  63.            Start-Process -Wait -FilePath "$setAclFilePath" -ArgumentList "-on", "`"$key`"", "-ot", "reg", "-actn", "setowner", "-ownr", "`"n:$userName`"", "-rec", "Yes", "-actn", "ace", "-ace", "`"n:$userName;p:full`"", "-rec", "Yes", "-log", "`"$($logFile.FullName)`"" -NoNewWindow -PassThru
  64.            #$logContent = Get-Content -Path $logFile.FullName
  65.            Write-Output ""
  66.            #Write-Output $logContent
  67.        }
  68.  
  69.    } catch {
  70.        Write-Host "Something went wrong when calling '$($MyInvocation.MyCommand.Name)' method:"
  71.        Write-Host ""
  72.        Write-Warning ($_.Exception)
  73.        Write-Host ""
  74.        Write-Error -Message ($_.Exception | Format-List * -Force | Out-String)
  75.        Write-Host ""
  76.        Write-Host "Press any key to exit..."
  77.        $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown")
  78.        Exit(1)
  79.    }
  80. }
  81.  
  82. function Show-GoodbyeScreen {
  83.    Write-Host "Operation Completed!" -BackgroundColor Black -ForegroundColor Green
  84.    Write-Host ""
  85.    Write-Host "Press any key to exit..."
  86.    $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown")
  87.    Exit(0)
  88. }
  89.  
  90. <#
  91. ===========================================================================================
  92. |                                                                                         |
  93. |                                         Main                                            |
  94. |                                                                                         |
  95. ===========================================================================================
  96. #>
  97.  
  98. [System.Console]::Title = "Get Full Registry Ownership Tool - by Elektro"
  99. [CultureInfo]::CurrentUICulture = "en-US"
  100.  
  101. $SetAclFilePath = "$env:ProgramFiles\SetACL\SetACL.exe"
  102. $RegKeys = "HKEY_CLASSES_ROOT", "HKEY_CURRENT_USER", "HKEY_LOCAL_MACHINE", "HKEY_USERS", "HKEY_CURRENT_CONFIG"
  103. $UserName = $env:UserName
  104.  
  105. try { Set-ExecutionPolicy -ExecutionPolicy "Unrestricted" -Scope "Process" } catch { }
  106.  
  107. Show-WelcomeScreen
  108. Confirm-Continue
  109. Get-RegistryOwnership -SetAclFilePath $SetAclFilePath -RegKeys $RegKeys -UserName $UserName
  110. Show-GoodbyeScreen
9  Programación / Scripting / [APORTE] [PowerShell] Automated AppX Package Installer en: 4 Marzo 2024, 15:19 pm
El siguiente script desarrollado en Powershell, buscará archivos de paquetes AppX (*.appx, *.appxbundle, *.msixbundle) dentro del directorio actual (sin recursividad), imprimirá información sobre el paquete, imprimirá un mensaje en caso de que el paquete ya esté instalado, e instalará el paquete en caso de que no esté instalado, manejando posibles errores durante instalación.

Es una herramienta muy útil en particular para quien (como yo) tenga completamente capada la Microsoft Store y sus funcionalidades en el sistema operativo, y necesite una forma de poder instalar paquetes de aplicaciones (*.appx, *.appxbundle, *.msixbundle) descargadas de forma local desde la Microsoft Store.





Código
  1. # --------------------------------------------- #
  2. # Automated AppX Package Installer - by Elektro #
  3. # --------------------------------------------- #
  4.  
  5. # This script will find any AppX package files within the current directory (without recursion),
  6. # print info about the package, print a message in case of the package is already installed,
  7. # and install the package in case of it is not installed, handling errors during installation.
  8.  
  9. # ---------------------------------------------------------------------
  10.  
  11. # Takes a string argument that points to an AppX package name or file,
  12. # then it uses a regular expression to match the package string pattern
  13. # and returns a custom object with the Name, Version, Architecture,
  14. # PublisherId and other properties.
  15. #
  16. # Parameters:
  17. #   -PackageString: A string that points to the file name
  18. #                   or full path of an AppX package file.
  19. #
  20. # Returns:
  21. #   A PSCustomObject object with these properties defined:
  22. #     [String] Name
  23. #     [String] Version
  24. #     [String] Architecture
  25. #     [String] PublisherId
  26. #     [String] FullName
  27. function Get-AppXPackageInfo {
  28.    param (
  29.        [Parameter(Mandatory=$true)] [string]$PackageString
  30.    )
  31.  
  32.    #$dirname = [System.IO.Path]::GetDirectoryName($PackageString)
  33.    #if ([string]::IsNullOrEmpty($dirname)) {
  34.    #    $dirname = $PWD
  35.    #}
  36.  
  37.    $filename = [System.IO.Path]::GetFileName($PackageString) -replace "(?i)\.appxbundle$", "" -replace "(?i)\.msixbundle$", "" -replace "(?i)\.appx$", ""
  38.  
  39.    $regex = '^(?<Name>.+?)_(?<Version>.+?)_(?<Architecture>.+?)_(?<chars>~)?_(?<PublisherId>.+)$'
  40.    $match = $filename -match $regex
  41.  
  42.    if (!$match) {
  43.        throw "Unable to parse the string package: '$PackageString'"
  44.    }
  45.  
  46.    [string]$packageName         = $matches['Name']
  47.    [string]$packageVersion      = $matches['Version']
  48.    [string]$packageArchitecture = $matches['Architecture']
  49.    [string]$packagePublisherId  = $matches['PublisherId']
  50.    [string]$chars               = $matches['chars']
  51.    [string]$packageFullName     = "${packageName}_${packageVersion}_${packageArchitecture}_${chars}_${packagePublisherId}"
  52.    #[string]$packageFullPath    = [System.IO.Path]::Combine($dirname, "$filename.Appx")
  53.  
  54.    [PSCustomObject]@{
  55.        Name = $packageName
  56.        Version = $packageVersion
  57.        Architecture = $packageArchitecture
  58.        PublisherId = $packagePublisherId
  59.        FullName = $packageFullName
  60.        #FullPath = $packageFullPath
  61.    }
  62. }
  63.  
  64. # Determines whether an Appx package matching the specified
  65. # name, version and architecture is installed in the system.
  66. #
  67. # Parameters:
  68. #   -Name........: The package name.
  69. #   -Version.....: The package version.
  70. #   -Architecture: The package architecture ("x86", "x64").
  71. #
  72. # Returns:
  73. #   $true if the AppX package is installed in the system,
  74. #   $false otherwise.
  75. function IsAppxPackageInstalled() {
  76.    param (
  77.        [Parameter(Mandatory=$true)] [string]$name,
  78.        [Parameter(Mandatory=$true)] [string]$version,
  79.        [Parameter(Mandatory=$true)] [string]$architecture
  80.    )
  81.  
  82.    if ($architecture -eq "neutral") {
  83.        $architecture = [System.Runtime.InteropServices.RuntimeInformation]::ProcessArchitecture
  84.    }
  85.  
  86.    $packages = Get-AppxPackage "$($name)*" -ErrorAction Stop | Where-Object {
  87.        $_.Name.ToLower()              -eq $name.ToLower()         -and
  88.        $_.Version.ToLower()           -eq $version.ToLower()      -and
  89.        "$($_.Architecture)".ToLower() -eq $architecture.ToLower()
  90.    }
  91.    return ($packages.Count -gt 0)
  92. }
  93.  
  94. <#
  95. ===========================================================================================
  96. |                                                                                         |
  97. |                                         Main                                            |
  98. |                                                                                         |
  99. ===========================================================================================
  100. #>
  101.  
  102. [System.Console]::Title = "Automated AppX Package Installer - by Elektro"
  103. [CultureInfo]::CurrentUICulture = "en-US"
  104.  
  105. try { Set-ExecutionPolicy -ExecutionPolicy "Unrestricted" -Scope "Process" } catch { }
  106.  
  107. # Hides the progress-bar for 'Add-AppxPackage' cmdlet in this script.
  108. # Thanks to @Santiago Squarzon for the tip: https://stackoverflow.com/questions/75716867
  109. # https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_preference_variables?view=powershell-7.3#progresspreference
  110. $ProgressPreference = "Ignore"
  111.  
  112. Do {
  113.    Clear-Host
  114.    Write-Output ""
  115.    Write-Output " $($host.ui.RawUI.WindowTitle)"
  116.    Write-Output " +=====================================================+"
  117.    Write-Output " |                                                     |"
  118.    Write-Output " | This script will find any AppX package files        |"
  119.    Write-Output " | within the current directory (without recursion),   |"
  120.    Write-Output " | print info about the package, print a message       |"
  121.    Write-Output " | in case of the package is already installed,        |"
  122.    Write-Output " | and install the package in case of it is            |"
  123.    Write-Output " | not installed, handling errors during installation. |"
  124.    Write-Output " |                                                     |"
  125.    Write-Output " +=====================================================+"
  126.    Write-Output ""
  127.    Write-Host " -Continue? (Y/N)"
  128.    $key = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
  129.    $char = $key.Character.ToString().ToUpper()
  130.    if ($char -ne "Y" -and $char -ne "N") {
  131.        [console]::beep(1500, 500)
  132.    }
  133. } while ($char -ne "Y" -and $char -ne "N")
  134. if ($char -eq "N") {Exit(1)} else {Clear-Host}
  135.  
  136. $appxFiles = Get-ChildItem -Path "$PWD" -Filter "*.appx*"
  137.  
  138. if ($appxFiles.Count -eq 0) {
  139.    Write-Warning "No Appx files were found in the current directory."
  140.    Write-Host ""
  141.    $LastExitCode = 2
  142. } else {
  143.    $appxFiles | ForEach-Object {
  144.        # The AppX package string. It can be a file name (with or without extension), or a full path.
  145.        $packageString = $_.FullName
  146.        $packageInfo = Get-AppXPackageInfo -PackageString $packageString
  147.        $nameVerArch = "$($packageInfo.Name) v$($packageInfo.Version) ($($packageInfo.Architecture))"
  148.        Write-Host "Package Info.:" -ForegroundColor Gray
  149.        Write-Host ($packageInfo | Format-List | Out-String).Trim() -ForegroundColor DarkGray
  150.        Write-Host ""
  151.  
  152.        $isInstalled = IsAppxPackageInstalled -Name $packageInfo.Name -Version $packageInfo.Version -Architecture $packageInfo.Architecture
  153.        if ($isInstalled) {
  154.            Write-Warning "Package $nameVerArch is already installed."
  155.            Write-Warning "Installation is not needed."
  156.        } else {
  157.            Write-Host "Package $nameVerArch is ready to install."
  158.            Write-Host "Installing package..."
  159.            try {
  160.                Add-AppxPackage -Path "$($_.FullName)" -ErrorAction Stop
  161.                Write-Host "Package $nameVerArch has been successfully installed." -BackgroundColor Black -ForegroundColor Green
  162.            } catch {
  163.                Write-Host "Error installing package $nameVerArch" -BackgroundColor Black -ForegroundColor Red
  164.                Write-Host ""
  165.                Write-Error -Message ($_.Exception | Format-List * -Force | Out-String)
  166.                $LastExitCode = 1
  167.                Break
  168.            }
  169.        }
  170.        Write-Host ""
  171.        $LastExitCode = 0
  172.    }
  173. }
  174.  
  175. Write-Host "Program will terminate now with exit code $LastExitCode. Press any key to exit..."
  176. $key = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
  177. Exit($LastExitCode)
10  Programación / Scripting / [APORTE] [PowerShell] Remove Windows Installer product registration for missing MSI packages 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



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. #>
Páginas: [1] 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 ... 105
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines