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

 

 


Tema destacado: Introducción a Git (Primera Parte)


  Mostrar Mensajes
Páginas: 1 2 3 4 5 6 7 8 9 10 [11] 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ... 1236
101  Informática / Hardware / Re: Imágenes y vídeos en mi USB están cifrados en: 5 Marzo 2024, 12:49 pm
Ya me dices algo (...) o al no tener el directorio de la cuenta antigua sería en vano.

Para poder llevar a cabo la posible solución que te indiqué, es necesario el archivo "NTUSER.DAT" que estaría ubicado en: "C:\Users\NOMBRE DE TU ANTIGUA CUENTA\NTUSER.DAT", sin eso, no sirve; si el directorio se eliminó al restablecer el sistema a la configuración de fábrica, entonces ya no nos sirve.

Qué lástima. Aunque, de todas formas, quizás el intento no hubiese valido mucho la pena. Para determinarlo con algo de confianza y exactitud habría que conocer exactamente que información maneja de forma interna el servicio de cifrado EFS para validar una cuenta de usuario y permitir el descifrado desde esa cuenta, y eso es algo que desconozco. No creo que sea información pública.



Bueno, si todavía sigues queriendo probar, se me ocurre una sugerencia que podrías intentar...

Esta sugerencia tiene el fin de intentar recuperar el archivo "NTUSER.DAT" que se borró en el procedimiento de ajustes de fábrica, y también el archivo "SECURITY" ubicado en "C:\Windows\System32\config" (aunque si puedes recuperar todo lo demás que hubiese en esta carpeta (las demás colmenas), mejor que mejor).

Para ello puedes utilizar un programa de recuperación de datos, como por ejemplo Recuva: https://www.ccleaner.com/es-es/recuva

Si nunca has usado este tipo de programas creo que es preferible que visualices algún tutorial en Youtube antes que leer un par de explicaciones cortas escritas por mi parte.

Nota: Para minimizar el riesgo de que algunas partes del archivo hayan sido sobreescritos por nuevos datos (y por ende, que no se puedan recuperar en su totalidad), sería conveniente que no hagas mucho uso del disco más allá del necesario, es decir, intentar no realizar demasiadas operaciones de escritura (intentar no descargar nada en ese disco, no crear archivos de tamaño muy pesado, etc). Solo hasta que hayas terminado de usar el programa de recuperación de datos. También es conveniente, en caso de que logres encontrar los archivos solicitados y también para minimizar el riesgo de sobreescritura, que, desde el programa de recuperación de datos, los archivos los recuperes enviándolos / guardándolos / reconstruyéndolos a otra unidad de disco, no al mismo disco en el que fueron eliminados.

Suerte.
102  Informática / Hardware / Re: Imágenes y vídeos en mi USB están cifrados en: 5 Marzo 2024, 05:19 am
Tengo un archivo llamado NTUSER.DAT en esa ubicación que indicas, que tendría que hacer con ella?


¿Pero el archivo reside en el directorio de la antigua cuenta de usuario, ¿no?, de lo contrario no sirve.

De acuerdo, en ese caso entiendo que en tu PC quedan rastros, al menos del directorio del perfil de usuario de la cuenta "Alex".

Ese archivo "NTUSER.DAT" contiene toda la rama del registro HKEY_CURRENT_USER de esa cuenta de usuario, incluyendo el SID, así que podría ser de utilidad para posibles soluciones como la sugerencia de @Daniel sobre "clonar" esa cuenta de usuario, usando el mismo nombre exacto y el mismo SID, y a ver si con mucha suerte eso es suficiente para que puedas descifrar los archivos...



A continuación te detallo los pasos a seguir. Pero te advierto que todo esto es un planteamiento teoríco que he desarrollado, jamás lo he probado, así que puede acabar siendo de inutilidad.

1.

Monta el archivo de colmena del registro "NTUSER.DAT" de la antigua cuenta de usuario de "Alex" usando el programa Regedit integrado en Windows, aunque puede que te sea más fácil usando el programa de terceros Registry Explorer (https://ericzimmerman.github.io/#!index.md), y yo en este ejemplo es el programa que usaré.

Simplemente haz click en la opción del menú: "File -> Load Hive" y cargas el archivo "NTUSER.DAT".

Una vez que has montado la colmena, y para recuperar el SID de esa cuenta de usuario, ubica el valor "RecycleBin" de la clave HKEY_CURRENT_USER/Environment como en la siguiente imagen:



Simplemente apunta esa cadena de texto que empieza por la letra "S". En mi caso sería: "S-1-5-21-4028340171-1815735104-1074574231-500"

(A menos que hayas configurado de forma atípica las papeleras de reciclaje, lo de arriba te debería funcionar para obtener el SID.)



2.

A continuación, carga el archivo de colmena "SECURITY" ubicado en: C:\Windows\System32\config, encuentra la clave que hace referecia al SID que apuntaste anteriormente, y en la subclave "sid" copia el contenido del valor que te muestro en la siguiente imagen:



Para ello simplemente haz click derecho sobre el valor, selecciona la opción del menú: "Copy -> Value data" y el contenido del valor se enviará al porpapales de Windows (ya sabes, utiliza CONTROL+V para pegar lo copiado).

En mi caso obtengo una cadena de texto como esta:
Código:
01-05-00-00-00-00-00-05-15-00-00-00-CB-97-1B-F0-40-EB-39-6C-97-B3-0C-40-F4-01-00-00

Pues bien, ahora reemplaza los guiones por comas, y quedará algo como esto:
Código:
01,05,00,00,00,00,00,05,15,00,00,00,CB,97,1B,F0,40,EB,39,6C,97,B3,0C,40,F4,01,00,00

Apúntate en algún sitio esa cadena de texto separada por comas.

Notas:
Obtener ese valor SID en Hexadecimal es esencial, por que no es simplemente una conversión a Hexadecimal, sino que además sigue un orden basado en la estructura que forman las partes de un valor SID.

En teoría, teniendo unicamente el SID del paso anterior, me refiero, el que empieza por la letra "S", se puede desglosar su estructura para obtener este formato de SID en Hexadecimal, pero yo no tengo muy claro como y cual es el orden de ese formato para desglosar las partes del SID correctamente.

Y el problema es que no estoy muy seguro de si tras los "ajustes de fábrica" realizados en tu PC quedarán rastros de estas claves necesarias para obtener el SID en formato Hexadecimal. Esperemos que si.



3.

Para proseguir con el intento de clonación de cuenta de usuario, más adelante necesitaremos obtener permisos de escritura para una clave muy sensible del registro de Windows...

Descárgate el programa de terceros por línea de comandos "SetACL" (no confundir con SetACL Studio): https://helgeklein.com/download/

Y una vez descargado el programa y, DESDE UNA CUENTA DE USUARIO CON PRIVILEGIOS DE ADMINISTRADOR, abres un prompt de la CMD en el directorio donde se encuentre el archivo "SetACL.exe" y escribes el siguiente comando en la consola:

Código:
SetACL.exe -on "HKEY_LOCAL_MACHINE\SECURITY\SAM\Domains\Account\Users" -ot "reg" -ace "n:%UserName%;p:full" -rec "Yes" -actn "ace"

(Si el comando te diese error entonces repite el procedimiento pero esta vez desde la cuenta integrada de Administrador de Windows. Para activar la cuenta integrada de Administrador escribe el siguiente comando en la CMD: net user administrator /active:yes , posteriormente inicias sesión en esa cuenta de Administrador y repites el comando de SetACL para modificar los permisos de esa clave de registro.)



4.

Lo último que queda por hacer, a ver como lo simplifico para que no te suponga mucha dificultad....

Observa este código (es un script del Registro de Windows):

Código
  1. Windows Registry Editor Version 5.00
  2.  
  3. [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\{SID}]
  4. "ProfileImagePath"=hex(2):{DIRECTORIO DE LA CUENTA DE USUARIO}
  5. "Flags"=dword:00000000
  6. "State"=dword:00000004
  7. "Sid"=hex:{SID HEXADECIMAL}
  8. "FullProfile"=dword:00000001
  9.  
  10. [HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Windows NT\CurrentVersion\ProfileList\{SID}]
  11. "ProfileImagePath"=hex(2):{DIRECTORIO DE LA CUENTA DE USUARIO}
  12. "Flags"=dword:00000000
  13. "State"=dword:00000004
  14. "Sid"=hex:{SID HEXADECIMAL}
  15. "FullProfile"=dword:00000001
  16.  
  17. [HKEY_LOCAL_MACHINE\SECURITY\SAM\Domains\Account\Users\Names\{NOMBRE DE USUARIO}]
  18. @=hex(9eb):
  19.  
  20. [HKEY_LOCAL_MACHINE\SECURITY\SAM\Domains\Account\Users\000009EB]
  21. "F"=hex:03,00,01,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,\
  22.  00,cd,fb,4c,b5,a8,6e,da,01,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,\
  23.  eb,03,00,00,01,02,00,00,14,02,00,00,00,00,00,00,00,00,00,00,01,00,00,00,00,\
  24.  00,00,00,00,00,00,00
  25. "V"=hex:00,00,00,00,f4,00,00,00,03,00,01,00,f4,00,00,00,08,00,00,00,00,00,00,\
  26.  00,fc,00,00,00,08,00,00,00,00,00,00,00,04,01,00,00,00,00,00,00,00,00,00,00,\
  27.  04,01,00,00,00,00,00,00,00,00,00,00,04,01,00,00,00,00,00,00,00,00,00,00,04,\
  28.  01,00,00,00,00,00,00,00,00,00,00,04,01,00,00,00,00,00,00,00,00,00,00,04,01,\
  29.  00,00,00,00,00,00,00,00,00,00,04,01,00,00,00,00,00,00,00,00,00,00,04,01,00,\
  30.  00,00,00,00,00,00,00,00,00,04,01,00,00,15,00,00,00,a8,00,00,00,1c,01,00,00,\
  31.  08,00,00,00,01,00,00,00,24,01,00,00,18,00,00,00,00,00,00,00,3c,01,00,00,18,\
  32.  00,00,00,00,00,00,00,54,01,00,00,18,00,00,00,00,00,00,00,6c,01,00,00,18,00,\
  33.  00,00,00,00,00,00,01,00,14,80,d4,00,00,00,e4,00,00,00,14,00,00,00,44,00,00,\
  34.  00,02,00,30,00,02,00,00,00,02,c0,14,00,44,00,05,01,01,01,00,00,00,00,00,01,\
  35.  00,00,00,00,02,c0,14,00,ff,07,0f,00,01,01,00,00,00,00,00,05,07,00,00,00,02,\
  36.  00,90,00,04,00,00,00,00,00,24,00,44,00,02,00,01,05,00,00,00,00,00,05,15,00,\
  37.  00,00,cb,97,1b,f0,40,eb,39,6c,97,b3,0c,40,eb,03,00,00,00,00,38,00,1b,03,02,\
  38.  00,01,0a,00,00,00,00,00,0f,03,00,00,00,00,04,00,00,de,a2,28,67,21,3e,d2,af,\
  39.  19,ad,5d,79,b0,c1,07,29,27,56,fc,20,d8,ad,66,f6,10,f2,68,fa,df,2a,f8,0f,00,\
  40.  00,18,00,ff,07,0f,00,01,02,00,00,00,00,00,05,20,00,00,00,20,02,00,00,00,00,\
  41.  14,00,5b,03,02,00,01,01,00,00,00,00,00,01,00,00,00,00,01,02,00,00,00,00,00,\
  42.  05,20,00,00,00,20,02,00,00,01,02,00,00,00,00,00,05,20,00,00,00,20,02,00,00,\
  43.  41,00,6c,00,65,00,78,00,41,00,6c,00,65,00,78,00,ff,ff,ff,ff,ff,ff,ff,ff,ff,\
  44.  ff,ff,ff,ff,ff,ff,ff,ff,ff,ff,ff,ff,ca,a7,80,01,02,00,00,07,00,00,00,02,00,\
  45.  02,00,00,00,00,00,f3,f1,77,17,ad,ca,a7,80,b1,5a,7d,a0,d4,a9,55,6e,02,00,02,\
  46.  00,00,00,00,00,2d,f6,ce,86,e6,76,c7,c4,6a,61,19,a9,ad,4a,1b,1a,02,00,02,00,\
  47.  00,00,00,00,52,8d,4d,94,18,cf,0d,6a,53,db,8f,8c,3c,81,23,95,02,00,02,00,00,\
  48.  00,00,00,17,79,7f,58,6e,de,ec,d8,70,2d,1b,b5,2f,f4,36,54
  49. "UserTile"=-
  50.  

Donde pone "{NOMBRE DE USUARIO}" debes colocar el nombre de la cuenta antigua cuenta de usuario de "Alex" (sin lo del paréntesis).

Donde pone "{SID}" debes colocar el SID (el que empieza por la letra "S") de esa cuenta de usuario.

Donde pone {DIRECTORIO DE LA CUENTA DE USUARIO} debe ir la ruta al directorio del perfil del usuario de "Alex" (por ejemplo: "C:\Users\Alex\")

Y donde pone {SID HEXADECIMAL} debe ir el SID en hexadecimal separado por comas que apuntaste en el paso anterior.

El valor de "{NOMBRE DE USUARIO}" y "{SID}" los puedes colocar directamente modificando ese código, pero los otros dos valores requieren una edición con un formato diferente.

Por mostrarte un ejemplo real, parte del código se vería así:

Código
  1. Windows Registry Editor Version 5.00
  2.  
  3. [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\S-1-5-21-4028340171-1815735104-1074574231-1003]
  4. "ProfileImagePath"=hex(2):43,00,3a,00,5c,00,55,00,73,00,65,00,72,00,73,00,5c,\
  5.  00,41,00,6c,00,65,00,78,00,00,00
  6. "Flags"=dword:00000000
  7. "State"=dword:00000004
  8. "Sid"=hex:01,05,00,00,00,00,00,05,15,00,00,00,cb,97,1b,f0,40,eb,39,6c,97,b3,0c,\
  9.  40,eb,03,00,00
  10. "FullProfile"=dword:00000001
  11.  
  12. [HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Windows NT\CurrentVersion\ProfileList\S-1-5-21-4028340171-1815735104-1074574231-1003]
  13. "ProfileImagePath"=hex(2):43,00,3a,00,5c,00,55,00,73,00,65,00,72,00,73,00,5c,\
  14.  00,41,00,6c,00,65,00,78,00,00,00
  15. "Flags"=dword:00000000
  16. "State"=dword:00000004
  17. "Sid"=hex:01,05,00,00,00,00,00,05,15,00,00,00,cb,97,1b,f0,40,eb,39,6c,97,b3,0c,\
  18.  40,eb,03,00,00
  19. "FullProfile"=dword:00000001

Creo que lo mejor es que cuando llegues a este punto, simplemente dime cual es el SID (el que empieza por la letra "S") y el SID separado por comas, y yo te modifico los valores del registro de forma adecuada para que finalmente ejecutes el script y a ver lo que acaba sucediendo... :xD

Pero me gustaría que comprobases si en las claves de registro HKEY_LOCAL_MACHINE\SECURITY\SAM\Domains\Account\Users y también en HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList quedasen rastros de la antigua cuenta de usuario de "Alex", más que nada para poder hacer las cosas intentando incrementar la probabilidad de éxito. Si quedasen rastros, exporta esas claves del registro y comparte el contenido del script del registro como yo he hecho.



Todos los pasos que mencioné anteriormente deberías probarlos en un "entorno seguro" como una máquina virtual (usando el programa de terceros VMWare Workstation Player, por ejemplo), aunque sinceramente creo que no es realmente necesario y lo único que podría pasar es que la solución no funcione. Pero bueno, no me hago responsable de un posible malfuncionamiento del sistema tras haber probado esta metodología teórica.

En caso de que esto lo vayas a probar en una máquina virtual, puedes crea una nueva cuenta de usuario con nombre "Alex", o como se llamase tu antigua cuenta de usuario desde donde se cifraron los archivos, y le otorgas permisos de Administrador.

Para administrar (crear, editar, borrar) cuentas de usuario de forma sencillita te sugiero utilizar el programa de terceros Quick User Manager (https://www.carifred.com/quick_user_manager/).

Si la creaste con cuenta de correo de Microsoft, hazlo con la misma cuenta de correo y mismo nombre, todo igual.

Aténtamente,
Elektro.
103  Sistemas Operativos / Windows / Re: ¿Cómo borrar el historial de archivos abiertos que se muestran en ventana Ejecutar? en: 4 Marzo 2024, 17:52 pm
La lista MRU (Most Recently Used) del diálogo "Ejecutar" se almacena en la clave de registro HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\RunMRU, por lo que una forma de eliminarlas como alternativa a recurrir a software de terceros es mediante el uso del siguiente comando que puedes utilizar en la CMD o en un batch-script:

Código:
REG DELETE "HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\RunMRU" /VA /F

O también puedes guardar el contenido de este script del Registro de Windows en un archivo por nombre "RunMRU_Clean.reg" y ejecutarlo:

RunMRU_Clean.reg
Código
  1. Windows Registry Editor Version 5.00
  2.  
  3. [-HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\RunMRU]



Las entradas adicionales que te aparecen al pulsar la tecla "F" pertenecen al historial de navegación de archivos de Internet Explorer. Este historial incluye entradas que se generan automáticamente al navegar por directorios y archivos en el Explorer de Windows.

Puedes eliminar todas esas entradas desde el applet del Panel de Control por nombre "Opciones de Internet" (InetCpl.cpl):

 

O también puedes hacerlo utilizando el siguiente comando:
Código
  1. rundll32.exe InetCpl.cpl,ClearMyTracksByProcess 1

Aquí tienes más valores que puedes usar, aparte del "1", para la función ClearMyTracksByProcess del applet InetCpl.cpl:

 - superuser.com | ClearMyTracksByProcess - all options?

Aténtamente,
Elektro.



CCleaner tiene la opción de eliminar todos esos historiales.

Y eso es verdad. ¿Quien quiere andarse con todas estas eliminaciones manuales pudiendo configurarlo mediante las opciones de limpieza del CCleaner?. Lo digo totalmente en serio, vamos, CCleaner + CCEnhancer + reglas de eliminación personalizadas resuelve la tediosa tarea de limpiar un sistema en profundidad.

Estoy aquí para ayudar a resolver dudas, incluyendo enseñar este tipo de "trucos", pero lo recomendable sería usar CCleaner para estas cosas como indica @Songoku.
104  Informática / Hardware / Re: Imágenes y vídeos en mi USB están cifrados en: 4 Marzo 2024, 16:04 pm
Parece evidente que estamos hablando de archivos cifrados mediante EFS (Encrypting File System) de Windows. Yo en tu lugar y para evitar que esto se vuelva a repetir, deshabilitaría los servicios relacionados con EFS y adicionalmente los de BitLocker (cifrado de dispositivos enteros), y los caparía / eliminaría del sistema operativo, para siempre. Es lo que yo decidí hacer hace ya siglos.

La solución de "clonar" la cuenta de usuario en una VM es ingeniosa, pero no creo que sea suficiente con usar el mismo nombre de usuario, tampoco estoy seguro de ello, pero quiero pensar que para poder descifrar los archivos también debería ser necesario que la cuenta de usuario tenga el mismo identificador único (SID), y puede que otras cosas más. Se podría realizar una mejor "clonación" de la cuenta de usuario si tuvieras una copia de seguridad del archivo de colmena (HIVE) del registro de Windows del usuario en cuestión ("C:\Users\Alex\NTUSER.DAT").

En caso contrario, no creo que puedas recuperar esos archivos a menos que logres acceso a la cuenta de usuario desde la cual se cifraron.

He leído que si mueves o copias los archivos cifrados a un disco con formato FAT32 o exFAT, se pierde el cifrado. (¿Tu USB tiene formarto NTFS?). Pero imagino que esta operación habrá que realizarla desde la cuenta de usuario original desde donde se cifraron. Tampoco estoy totalmente seguro de ello.

Quizás otros usuarios te puedan brindar alguna posible solución poco convencional. No hagas nada por el momento y espera un poco a ver. Suerte.

Aténtamente,
Elektro.
105  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
106  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)
107  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. #>
108  Programación / Scripting / [APORTE] [BATCH] FFMPEG | Convert Video to MP4 - Sony Vegas Compatible en: 4 Marzo 2024, 14:59 pm
El siguiente Batch-script, dependiente del programa de terceros FFMPEG, tiene la función de convertir un archivo de video (por lo general, MKV) a un formato MP4 que será compatible para la edición del video en los productos de Sony VEGAS.





Código
  1. @Echo OFF & CHCP 1252 >NUL & Title FFMPEG Convert Video to MP4 - Sony Vegas Compatible - Tool by Elektro
  2.  
  3. ECHO: This script will convert the source video file
  4. ECHO: to a MP4 video compatible with Sony Vegas.
  5.  
  6. IF "%~1" EQU "" (
  7.    ECHO: ERROR. INPUT FILE IS NOT DEFINED.
  8.    ECHO: YOU MUST DROP A MKV FILE TO THIS BATCH-FILE.
  9.    ECHO+
  10.    ECHO: This program will exit now...
  11.    ECHO+
  12.    Pause
  13.    Exit /B 1
  14. )
  15.  
  16. ECHO: Input  file: "%~1"
  17. ECHO: Output file: "%~dpn1_VEGAS.mp4"
  18.  
  19. CHOICE /C YN /M "Continue?"
  20. IF %ERRORLEVEL% EQU 2 (
  21.    Exit /B 1
  22. ) ELSE (
  23.    CLS
  24. )
  25.  
  26. IF NOT EXIST "%~dp0ffmpeg.exe" (
  27.    ECHO: ERROR. FILE DOES NOT EXIST: "%~dp0ffmpeg.exe"
  28.    ECHO: This program will exit now...
  29.    ECHO+
  30.    Pause
  31.    Exit /B 1
  32. )
  33.  
  34. :::::::::::::::::::::::::::::::::::::::::::::::::::::::
  35.  
  36. REM How to encode Vegas-compatible H.264 file using FFmpeg:
  37. REM http://www.konstantindmitriev.ru/blog/2014/03/02/how-to-encode-vegas-compatible-h-264-file-using-ffmpeg/
  38.  
  39. ECHO+Choose a encoding preset:
  40. ECHO+ [1] ultrafast
  41. ECHO+ [2] superfast
  42. ECHO+ [3] veryfast
  43. ECHO+ [4] faster
  44. ECHO+ [5] fast
  45. ECHO+ [6] medium – default preset
  46. ECHO+ [7] slow
  47. ECHO+ [8] slower
  48. ECHO+ [9] veryslow
  49. ECHO+ [0] Exit
  50. CHOICE /C "0123456789" /M ""
  51.  
  52. IF %ERRORLEVEL% EQU  1 (Exit)
  53. IF %ERRORLEVEL% EQU  2 (SET "preset=ultrafast")
  54. IF %ERRORLEVEL% EQU  3 (SET "preset=superfast")
  55. IF %ERRORLEVEL% EQU  4 (SET "preset=veryfast")
  56. IF %ERRORLEVEL% EQU  5 (SET "preset=faster")
  57. IF %ERRORLEVEL% EQU  6 (SET "preset=fast")
  58. IF %ERRORLEVEL% EQU  7 (SET "preset=medium")
  59. IF %ERRORLEVEL% EQU  8 (SET "preset=slow")
  60. IF %ERRORLEVEL% EQU  9 (SET "preset=slower")
  61. IF %ERRORLEVEL% EQU 10 (SET "preset=veryslow")
  62.  
  63. :: SET "forcedFPS=-r 23.976"
  64. CLS
  65.  
  66. "%~dp0ffmpeg.exe" %forcedFPS% -y -loglevel info -i "%~1" -c:v libx264 -preset %preset% -crf 23 -c:a aac -strict experimental -tune fastdecode -pix_fmt yuv420p -b:a 192k -ar 48000 %forcedFPS% "%~n1_VEGAS.mp4"
  67.  
  68. If %ERRORLEVEL% EQU 0 (
  69.    CLS
  70.    Color A
  71.    Echo+
  72.    Echo: Video conversion completed successfully.    | MORE | MORE
  73.    Echo: Input.: "%~1"                               | MORE
  74.    Echo: Output: "%~dpn1_VEGAS.mp4"                  | MORE
  75.    Echo+
  76.    Pause
  77.    Exit /B 0
  78. ) ELSE (
  79.    Color C
  80.    Echo+
  81.    Echo: Video conversion completed with errors.     | MORE | MORE
  82.    Echo: Input.: "%~1"                               | MORE
  83.    Echo: Output: "%~dpn1_VEGAS.mp4"                  | MORE
  84.    Echo+
  85.    Pause
  86.    Exit /B 1
  87. )
  88.  
109  Programación / Scripting / [APORTE] [PowerShell] IrfanView | Crop image files en: 4 Marzo 2024, 14:48 pm
El siguiente script desarrollado en PowerShell y dependiente del programa de terceros IrfanView, sirve para hacer un recorte (crop) específico en los archivos de imagen del directorio actual.

En la sección "Variables" dentro del script pueden personalizar los puntos de recorte (x, y, width, height), así como la calidad de codificación para archivos JPG entre otras cosas configurables.





Código
  1. <#
  2. ===========================================================================================
  3. |                                                                                         |
  4. |                                        Variables                                        |
  5. |                                                                                         |
  6. ===========================================================================================
  7. #>
  8.  
  9. $inputDirectoryPath = "$PSScriptRoot"
  10. $fileNameSearchPattern = "*.*"
  11. $imageExts = @("avif", "bmp", "jp2", "jpg", "png", "tga", "tif", "webp")
  12. $recurse = $false
  13.  
  14. $irfanviewFullPath = "C:\Program Files\IrfanView\i_view64.exe"
  15.  
  16. # Cropping values
  17. $x      = 12
  18. $y      = 20
  19. $width  = 620
  20. $height = 560
  21.  
  22. # For cropping images that are jpg/jpeg
  23. $jpgQuality = 95
  24.  
  25.  
  26. <#
  27. ===========================================================================================
  28. |                                                                                         |
  29. |                                    Functions                                            |
  30. |                                                                                         |
  31. ===========================================================================================
  32. #>
  33.  
  34. function Show-WelcomeScreen {
  35.    Clear-Host
  36.    Write-Host ""
  37.    Write-Host " $($host.ui.RawUI.WindowTitle)"
  38.    Write-Host " +=========================================+"
  39.    Write-Host " |                                         |"
  40.    Write-Host " | This script will search for image files |"
  41.    Write-Host " | in the current working directory, and   |"
  42.    Write-Host " | use IrfanView to crop them using the    |"
  43.    Write-Host " | specified cropping settings.            |"
  44.    Write-Host " |                                         |"
  45.    Write-Host " +=========================================+"
  46.    Write-Host ""
  47.    Write-Host " Script Settings         " -ForegroundColor DarkGray
  48.    Write-Host " ========================" -ForegroundColor DarkGray
  49.    Write-Host " Input Directory Path....: $inputDirectoryPath" -ForegroundColor DarkGray
  50.    Write-Host " Recursive File Search...: $recurse" -ForegroundColor DarkGray
  51.    Write-Host " Search File Name Pattern: $fileNameSearchPattern" -ForegroundColor DarkGray
  52.    Write-Host " Search File Extensions..: $($imageExts -join ', ')" -ForegroundColor DarkGray
  53.    Write-Host " IrfanView Full Path.....: $irfanviewFullPath" -ForegroundColor DarkGray
  54.    Write-Host " JPG Quality.............: $jpgQuality%" -ForegroundColor DarkGray
  55.    Write-Host " Cropping.values.........: X=$x, Y=$y, Width=$width, Height=$height" -ForegroundColor DarkGray
  56.    Write-Host ""
  57. }
  58.  
  59. function Confirm-Continue {
  60.    Write-Host " Press 'Y' key to continue or 'N' to exit."
  61.    Write-Host ""
  62.    Write-Host " -Continue? (Y/N)"
  63.    do {
  64.        $key = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
  65.        $char = $key.Character.ToString().ToUpper()
  66.        if ($char -ne "Y" -and $char -ne "N") {
  67.            [console]::beep(1500, 500)
  68.        }
  69.    } while ($char -ne "Y" -and $char -ne "N")
  70.    if ($char -eq "N") {Exit(1)}
  71. }
  72.  
  73. function Validate-Parameters {
  74.  
  75.    if (-not (Test-Path -LiteralPath $inputDirectoryPath -PathType Container)) {
  76.        Write-Host " Input directory path does not exists!" -BackgroundColor Black -ForegroundColor Red
  77.        Write-Host ""
  78.        Write-Host " Press any key to exit..."
  79.        $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown")
  80.        Exit(1)
  81.    }
  82.  
  83.    if (-not (Test-Path -LiteralPath $irfanviewFullPath -PathType Leaf)) {
  84.        Write-Host " Irfanview file path does not exists!" -BackgroundColor Black -ForegroundColor Red
  85.        Write-Host ""
  86.        Write-Host " Press any key to exit..."
  87.        $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown")
  88.        Exit(1)
  89.    }
  90.  
  91.    if ($imageExts.Count -eq 0) {
  92.        Write-Host " No image file extensions were specified!" -BackgroundColor Black -ForegroundColor Red
  93.        Write-Host ""
  94.        Write-Host " Press any key to exit..."
  95.        $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown")
  96.        Exit(1)
  97.    }
  98.  
  99. }
  100.  
  101. function Crop-Files {
  102.    Clear-Host
  103.  
  104.    $imageFiles = $null
  105.    if ($recurse) {
  106.        $imageFiles = Get-ChildItem -LiteralPath $inputDirectoryPath -Filter $fileNameSearchPattern -Recurse | Where-Object { $imageExts -contains $_.Extension.ToLower().TrimStart('.') }
  107.    } else {
  108.        $imageFiles = Get-ChildItem -LiteralPath $inputDirectoryPath -Filter $fileNameSearchPattern | Where-Object { $imageExts -contains $_.Extension.ToLower().TrimStart('.') }
  109.    }
  110.  
  111.    foreach ($imageFile in $imageFiles) {
  112.        Write-Host " Cropping file: $($imageFile.FullName.Replace($inputDirectoryPath, "."))"
  113.  
  114.        $exitCode = $null
  115.        try {
  116.            $process = New-Object System.Diagnostics.Process
  117.            $process.StartInfo.FileName = $irfanviewFullPath
  118.            $process.StartInfo.Arguments = "`"$($imageFile.FullName)`" /crop=($x,$y,$width,$height) /jpgq=$jpgQuality /convert=""$($imageFile.FullName)"""
  119.            $process.StartInfo.UseShellExecute = $false
  120.            $started  = $process.Start() | Out-Null
  121.            $exited   = $process.WaitForExit()
  122.            $exitCode = $process.ExitCode
  123.        } catch {
  124.            Write-Host ""
  125.            Write-Host " Error running IrfanView process." -BackgroundColor Black -ForegroundColor Red
  126.            Write-Host ""
  127.            Write-Error -Message ($_.Exception.Message)
  128.            Write-Host ""
  129.            Write-Host " Press any key to exit..."
  130.            $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown")
  131.            Exit(1)
  132.        }
  133.  
  134.        if ($exitCode -eq 0) {
  135.            Write-Host " File cropped successfully." -ForegroundColor DarkGreen
  136.            Write-Host ""
  137.        } else {
  138.            Write-Host " Error cropping file. IrfanView Exit Code: $exitCode" -BackgroundColor Black -ForegroundColor Red
  139.            Write-Host ""
  140.            Write-Host " Press any key to ignore and continue..."
  141.            $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown")
  142.        }
  143.    }
  144. }
  145.  
  146. function Show-GoodbyeScreen {
  147.    Write-Host " Operation Completed!" -BackgroundColor Black -ForegroundColor Green
  148.    Write-Host ""
  149.    Write-Host " Press any key to exit..."
  150.    $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown")
  151.    Exit(0)
  152. }
  153.  
  154. <#
  155. ===========================================================================================
  156. |                                                                                         |
  157. |                                         Main                                            |
  158. |                                                                                         |
  159. ===========================================================================================
  160. #>
  161.  
  162. [System.Console]::Title = "Crop image files - by Elektro"
  163. #[System.Console]::SetWindowSize(146, 27)
  164. [CultureInfo]::CurrentUICulture = "en-US"
  165.  
  166. try { Set-ExecutionPolicy -ExecutionPolicy "Unrestricted" -Scope "Process" } catch { }
  167.  
  168. Show-WelcomeScreen
  169. Validate-Parameters
  170. Confirm-Continue
  171. Crop-Files
  172. Show-GoodbyeScreen
  173.  
110  Programación / Scripting / [APORTE] [PowerShell] IrfanView | Convert image files to JPG en: 4 Marzo 2024, 14:45 pm
El siguiente script desarrollado en PowerShell y dependiente del programa de terceros IrfanView, sirve para convertir todos los archivos de imagen del directorio actual, a formato JPG.

En la sección "Variables" dentro del script pueden personalizar la calidad de codificación JPG y los tipos de archivos de imagen a procesar entre otras cosas configurables.





Código
  1. <#
  2. ===========================================================================================
  3. |                                                                                         |
  4. |                                        Variables                                        |
  5. |                                                                                         |
  6. ===========================================================================================
  7. #>
  8.  
  9. $inputDirectoryPath = "$PSScriptRoot"
  10. $fileNameSearchPattern = "*.*"
  11. $imageExts = @("avif", "bmp", "jp2", "jpg", "png", "tga", "tif", "webp")
  12. $recurse = $false
  13.  
  14. $irfanviewFullPath = "C:\Program Files\IrfanView\i_view64.exe"
  15. $jpgQuality = 95
  16. $overwriteConfirm = $true
  17. $sendToRecycleBinConvertedFiles = $true
  18.  
  19. <#
  20. ===========================================================================================
  21. |                                                                                         |
  22. |                                    Functions                                            |
  23. |                                                                                         |
  24. ===========================================================================================
  25. #>
  26.  
  27. function Show-WelcomeScreen {
  28.    Clear-Host
  29.    Write-Host ""
  30.    Write-Host " $($host.ui.RawUI.WindowTitle)"
  31.    Write-Host " +===========================================+"
  32.    Write-Host " |                                           |"
  33.    Write-Host " | This script will search for image files   |"
  34.    Write-Host " | in the current working directory, and use |"
  35.    Write-Host " | IrfanView to convert them to JPG format.  |"
  36.    Write-Host " |                                           |"
  37.    Write-Host " +===========================================+"
  38.    Write-Host ""
  39.    Write-Host " Script Settings         " -ForegroundColor DarkGray
  40.    Write-Host " ========================" -ForegroundColor DarkGray
  41.    Write-Host " Input Directory Path....: $inputDirectoryPath" -ForegroundColor DarkGray
  42.    Write-Host " Recursive File Search...: $recurse" -ForegroundColor DarkGray
  43.    Write-Host " Search File Name Pattern: $fileNameSearchPattern" -ForegroundColor DarkGray
  44.    Write-Host " Search File Extensions..: $($imageExts -join ', ')" -ForegroundColor DarkGray
  45.    Write-Host " IrfanView Full Path.....: $irfanviewFullPath" -ForegroundColor DarkGray
  46.    Write-Host " JPG Quality.............: $jpgQuality%" -ForegroundColor DarkGray
  47.    Write-Host " Confirm Overwrite JPG...: $overwriteConfirm" -ForegroundColor DarkGray
  48.    Write-Host " Recycle Converted Files.: $sendToRecycleBinConvertedFiles" -ForegroundColor DarkGray
  49.    Write-Host ""
  50. }
  51.  
  52. function Confirm-Continue {
  53.    Write-Host " Press 'Y' key to continue or 'N' to exit."
  54.    Write-Host ""
  55.    Write-Host " -Continue? (Y/N)"
  56.    do {
  57.        $key = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
  58.        $char = $key.Character.ToString().ToUpper()
  59.        if ($char -ne "Y" -and $char -ne "N") {
  60.            [console]::beep(1500, 500)
  61.        }
  62.    } while ($char -ne "Y" -and $char -ne "N")
  63.    if ($char -eq "N") {Exit(1)}
  64. }
  65.  
  66. function Validate-Parameters {
  67.  
  68.    if (-not (Test-Path -LiteralPath $inputDirectoryPath -PathType Container)) {
  69.        Write-Host " Input directory path does not exists!" -BackgroundColor Black -ForegroundColor Red
  70.        Write-Host ""
  71.        Write-Host " Press any key to exit..."
  72.        $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown")
  73.        Exit(1)
  74.    }
  75.  
  76.    if (-not (Test-Path -LiteralPath $irfanviewFullPath -PathType Leaf)) {
  77.        Write-Host " Irfanview file path does not exists!" -BackgroundColor Black -ForegroundColor Red
  78.        Write-Host ""
  79.        Write-Host " Press any key to exit..."
  80.        $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown")
  81.        Exit(1)
  82.    }
  83.  
  84.    if ($imageExts.Count -eq 0) {
  85.        Write-Host " No image file extensions were specified!" -BackgroundColor Black -ForegroundColor Red
  86.        Write-Host ""
  87.        Write-Host " Press any key to exit..."
  88.        $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown")
  89.        Exit(1)
  90.    }
  91.  
  92. }
  93.  
  94. function Convert-Files {
  95.    Clear-Host
  96.    Add-Type -AssemblyName Microsoft.VisualBasic
  97.  
  98.    $imageFiles = $null
  99.    if ($recurse) {
  100.        $imageFiles = Get-ChildItem -LiteralPath $inputDirectoryPath -Filter $fileNameSearchPattern -Recurse | Where-Object { $imageExts -contains $_.Extension.ToLower().TrimStart('.') }
  101.    } else {
  102.        $imageFiles = Get-ChildItem -LiteralPath $inputDirectoryPath -Filter $fileNameSearchPattern | Where-Object { $imageExts -contains $_.Extension.ToLower().TrimStart('.') }
  103.    }
  104.  
  105.    foreach ($imageFile in $imageFiles) {
  106.        Write-Host " Converting to JPG: $($imageFile.FullName.Replace($inputDirectoryPath, "."))"
  107.  
  108.        $fileNameWithoutExtension = [System.IO.Path]::GetFileNameWithoutExtension($imageFile.Name)
  109.        $outputFilePath = Join-Path -Path ($imageFile.Directory.FullName) -ChildPath "$fileNameWithoutExtension.jpg"
  110.  
  111.        if ((Test-Path -LiteralPath $outputFilePath -PathType Leaf) -and ($overwriteConfirm)) {
  112.            # El archivo no existe o no se debe sobrescribir
  113.            Write-Warning " Output JPG file already exists but `$overwriteConfirm variable is disabled."
  114.            Write-Warning " The output JPG file will be overwitten if you continue."
  115.            Write-Host ""
  116.            Confirm-Continue
  117.            Write-Host ""
  118.        }
  119.  
  120.        $exitCode = $null
  121.        try {
  122.            $procStartInfo = New-Object System.Diagnostics.ProcessStartInfo
  123.            $procStartInfo.FileName = $irfanviewFullPath
  124.            $procStartInfo.Arguments = "`"$($imageFile.FullName)`" /jpgq=$jpgQuality /convert=`"$outputFilePath`""
  125.            $procStartInfo.UseShellExecute = $false
  126.            $process = New-Object System.Diagnostics.Process
  127.            $process.StartInfo = $procStartInfo
  128.            $process.Start() | Out-Null
  129.            $process.WaitForExit()
  130.            $exitCode = $process.ExitCode
  131.        } catch {
  132.            Write-Host ""
  133.            Write-Host " Error running IrfanView process." -BackgroundColor Black -ForegroundColor Red
  134.            Write-Host ""
  135.            Write-Error -Message ($_.Exception.Message)
  136.            Write-Host ""
  137.            Write-Host " Press any key to exit..."
  138.            $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown")
  139.            Exit(1)
  140.        }
  141.  
  142.        if ($exitCode -eq 0) {
  143.            Write-Host " File converted successfully." -ForegroundColor DarkGreen
  144.            if ($sendToRecycleBinConvertedFiles) {
  145.                [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile($imageFile.FullName, 'OnlyErrorDialogs', 'SendToRecycleBin')
  146.                Write-Host " File sent to recycle bin." -ForegroundColor DarkGray
  147.            }
  148.            Write-Host ""
  149.        } else {
  150.            Write-Host " Error converting file to JPG. IrfanView Exit Code: $exitCode" -BackgroundColor Black -ForegroundColor Red
  151.            Write-Host ""
  152.        }
  153.    }
  154. }
  155.  
  156. function Show-GoodbyeScreen {
  157.    Write-Host " Operation Completed!" -BackgroundColor Black -ForegroundColor Green
  158.    Write-Host ""
  159.    Write-Host " Press any key to exit..."
  160.    $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown")
  161.    Exit(0)
  162. }
  163.  
  164. <#
  165. ===========================================================================================
  166. |                                                                                         |
  167. |                                         Main                                            |
  168. |                                                                                         |
  169. ===========================================================================================
  170. #>
  171.  
  172. [System.Console]::Title = "Convert image files to JPG - by Elektro"
  173. #[System.Console]::SetWindowSize(146, 27)
  174. [CultureInfo]::CurrentUICulture = "en-US"
  175.  
  176. try { Set-ExecutionPolicy -ExecutionPolicy "Unrestricted" -Scope "Process" } catch { }
  177.  
  178. Show-WelcomeScreen
  179. Validate-Parameters
  180. Confirm-Continue
  181. Convert-Files
  182. Show-GoodbyeScreen
  183.  
  184.  
Páginas: 1 2 3 4 5 6 7 8 9 10 [11] 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ... 1236
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines